Spring doesn't correctly serialize JSON to Java Map

Zubaer Rahman

I have a form that contains multiple radio inputs and one textarea input that I send using axios from a ReactJs client. The request looks like this:

  axios.post("/wellbeing/" + params.wellbeingSurveyType, { formAnswersJson: formAnswers })
    .then(res => {
      // logic
    })
    .catch(err => {
      // logic
    })

The 'formAnswers' object looks like this: enter image description here

I then receive the request from a Spring controller that looks like the following:

    @PostMapping("{wellbeingSurveyType}")
    public WellbeingSurveySubmission submitSurvey(
            @PathVariable WellbeingSurveyType wellbeingSurveyType,
            @RequestBody String formAnswersJson) throws JsonProcessingException {
        var result = new ObjectMapper().readValue(formAnswersJson, HashMap.class);
        return new WellbeingSurveySubmission(); //ignore this
    }

When I call the 'toString()' method on the result object it seems to correctly print out the map values: enter image description here

But when I try to actually operate on the object (which is parsed as a LinkedHashMap) I cannot access the keys or values: enter image description here

When I try to open up the object using the debugging tool it seems to store a reference to itself as a value: enter image description here

The result I want is simply a Map<String, String> that represents the JSON but I am unsure why this behavior is happening.

Any help or tips on how to do this in a better way would be greatly appreciated, thank you.

Zubaer Rahman

Alright the best way I found to make this work was to deconstruct the JSON object in the axios post request like so:

axios.post("/wellbeing/" + params.wellbeingSurveyType, { ...formAnswers })
        .then(res => {
          // logic
        })
        .catch(err => {
          // logic
        })

Works better as if I just pass the formAnswers object it unnecessarily wraps the object i.e. A hashmap that contains a single key-value pair 'formAnswers'.

Although as The Frozen One mentioned, it would be better to define a dedicated form object and take it as a param in the spring controller.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324200457&siteId=291194637