Home > Mobile >  JSON Deserialization issue : Error deserialize JSON value into type
JSON Deserialization issue : Error deserialize JSON value into type

Time:05-19

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??

CodePudding user response:

The type of the value C is String, so the object mapper escapes all illegal characters a wraps the string in quotes.

You could make C an another map:

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

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

Or you can create custom POJO and use @JsonRawValue annotation:

public class MyPojo{

   private String a;

   @JsonRawValue
   private String c;

   // getter and setters
}

MyPojo m = new MyPojo();
m.setA("b");
m.setB("{\"a\" :3, \"b\" : 5}");

objectmapper.writeValueAsString(m);

From the documentation:

Marker annotation that indicates that the annotated method or field should be serialized by including literal String value of the property as is, without quoting of characters. This can be useful for injecting values already serialized in JSON or passing javascript function definitions from server to a javascript client. Warning: the resulting JSON stream may be invalid depending on your input value.

The client error meaning probably is that it can't deserialize String into an Object (it expects { instead of ").

CodePudding user response:

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}}

  • Related