0

I am trying to return the json object into the hashmap of response entity object along with other fields, but I getting something else for the fields where the corresponding value is a json object.

I tried debugging but every hashmap in the response flow was having the required response structure.

I tried sending this from the backend:

HashMap<String, Object> hashMap = new HashMap<>();
        HashMap<String, Object> hashMap2 = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("key", "dummy value");
        hashMap2.put("key", "dummy value");
        hashMap2.put("new key", jsonObject);
        hashMap.put("data", jsonObject);
        hashMap.put("data2", hashMap2);
        hashMap.put("extra field", "extra value");
        return new ResponseEntity<>(hashMap, HttpStatusCode.valueOf(200));

And I am getting this in the response:

{
    "data": {
        "empty": false,
        "mapType": "java.util.HashMap"
    },
    "data2": {
        "new key": {
            "empty": false,
            "mapType": "java.util.HashMap"
        },
        "key": "dummy value"
    },
    "extra field": "extra value"
}

2 Answers 2

2

In Spring Boot, you do not have to box the object that you are trying to return as JSON to the client inside of a HashMap.

Instead, typically one writes a DTO (Data Transfer Object) class that resembles the JSON that you want to return. For example, if I want to return:

{
  "foo": "bar",
  "fooList": ["bar", "bar", "bar"],
  "fooObject": { "field": "..." }
}

Then in Java, I'd write a DTO class as follows:

public class MyDTO {
  private String foo;
  private String[] fooList; // Can be a list as well
  private FooObject fooObject;

  // Getters to get access to the fields here
}

public class FooObject {
  private Object object;
  // Getters to get access to the fields here
}

Then, to return this with Spring Boot, you just set it as the object on the ResponseEntity: return new ResponseEntity<>(new MyDTO(...), HttpStatusCode.valueOf(200));

I would highly suggest that you follow the approach of creating a DTO class specific to the response that you want to return.

1
  • Thanks !!! Got what was going wrong Commented Jun 14, 2023 at 18:17
1

I know this is a old one. But there are many cases where JSONObject is being used to return the response. Use .toMap() of JSONObject to return the JSON object. In case of List / JSONArray object use .toList(). This will give the right response message.

Not the answer you're looking for? Browse other questions tagged or ask your own question.