Home > OS >  Spring boot variable/nested request body
Spring boot variable/nested request body

Time:10-22

I am working on a Spring Boot application that allows users to upload logic expression to the server. A web app allows them to visually create the expression. The result of the web app looks something like this

{
  "id": "someId",
  "fullexpression": {
    "left": "a",
    "operator": "AND",
    "right": {
        "left": {
            "left": "x",
            "operator": "AND",
            "right": "y",
        }
        "operator": "OR",
        "right": "z"
    }
  }
}

The above example describes the expression a AND ((x AND y) OR z).

I've found a Baeldung article that says:

the type we annotate with the @RequestBody annotation must correspond to the JSON sent from our client-side controller

If I understood the article correctly, it's not possible to do this directly. What is the best way to build a Spring Boot rest controller that allows a RequestBody to be nested like this? Of course I could always turn the JSON into a string on the client's side, and parse it in the rest controller but that doesn't really seem elegant.

CodePudding user response:

Define the RequestBody parameter as a JsonNode:

public <something> myService(@RequestBody JsonNode jsonNode) {}

CodePudding user response:

You might use a class that looks like :

public class Form {
    private String id;
    private Expression fullexpression;

    // constructor, getters and setters
}

where the class Expression has the fields left, operator (String), and right.

Since the type of left and right fields can be String or Expression, I would suggest you to set their type to Map<String,Expression> or JsonNode.. but I didn't test yet.

  • Related