Receiving JSON parameter contains ${} cause error in Spring Boot

Viewed 46

When the JSON I received the request contains ${}, the ${} is removed from the received object.

requested JSON

{
  "name":"$123$",
  "str1":"${str1}",
  "str2":"${str222",
  "str3":"${str3}333",
  "str4":"${str4}44444"
}

Controller

@RestController
public class TestController {
    @PostMapping("std")
    public Std test$2(@RequestBody Std std) {
        return std;
    }
}

Std.java

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Std {
    private String name;
    private String str1;
    private String str2;
    private String str3;
    private String str4;
    private String aa;
}

Result

{
"name": "$123$",
"str1": "str1",
"str2": "${str222",
"str3": "str3333",
"str4": "str444444"
}

When I manually parse JSON through code, the result is correct. The output JSON contains ${}. like this

    public void test() {
        try {
            String str = "{\n" +
                    "  \"name\":\"$123$\",\n" +
                    "  \"str1\":\"${str1}\",\n" +
                    "  \"str2\":\"${str2}22\",\n" +
                    "  \"str3\":\"${str3}333\",\n" +
                    "  \"str4\":\"${str4}44444\"\n" +
                    "}";
            Std std = JSON.parseObject(str, Std.class);
            System.out.println(JSON.toJSONString(std));
            Std std1 = objectMapper.readValue(str, Std.class);
            System.out.println(objectMapper.writeValueAsString(std1));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

Any help will be appreciated!

1 Answers

The ${variableName} notation is used in Spring Boot for the purpose of importing the values of configuration variables or environment variables. This is the root cause for the issue shown above.

The problem can be fixed in 2 ways -

  1. Replace ${ and } with a different de-limiter character

    Example: Use #data# instead of ${data}

    This approach is easy to implement as it can be done with small code change.

  2. Add an explicit escape sequence for the closing brace, I.E., for } character in the input JSON.

    This approach is difficult to implement, as it it may require more code changes than the other approach.

Related