Search code examples
javajsonjavabeansjson-deserialization

JSON Deserialization issue : Error deserialize JSON value into type


I have a composite object like below:

Map<String, Object> m = new HashMap<>();
m.put("a", "b");
m.put("c", "{\"a\" :3, \"b\" : 5}");

           
m = {a=b, c={"a" :3, "b" : 5}}

I have to submit this request via https call in order to deserialize to a java object, hence i converted this to JSON string, using,

objectmapper.writeValueAsString(m)

when i convert it , it is appending quotes to the value of c:

{"a":"b","c":"{\"a\" :3, \"b\" : 5}"}

and While deserializing this object at the client side, the request fails saying "Error deserialize JSON value into type: class"

Any help??


Solution

  • You better use JSONObject for c value:

    JSONObject json = new JSONObject();
    json.put("a", 3);
    json.put("b", 5);
    
    Map<String, Object> m = new HashMap<>();
    m.put("a", "b");
    m.put("c", json);
    

    Complete code:

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import net.minidev.json.JSONObject;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public static void main(String[] args) throws JsonProcessingException {
    
        JSONObject json = new JSONObject();
        json.put("a", 3);
        json.put("b", 5);
    
        Map<String, Object> m = new HashMap<>();
        m.put("a", "b");
        m.put("c", json);
    
    
        ObjectMapper objectMapper = new ObjectMapper();
        String valueAsString = objectMapper.writeValueAsString(m);
    
        System.out.println(valueAsString);
    }
    

    The output is:

    {"a":"b","c":{"a":3,"b":5}}