简体   繁体   中英

Json: Deserialization error while using Gson library

I have json string that should be converted back to a Map type.

Json used:

 String jsonString = "{
    "varA": "<math><mrow><mn>8</mn></mrow></math>",
    "varB": "<math><mrow><mi>m</mi></mrow></math>",
    "ans": "<math><mrow><mn>8</mn><mo>&#8290;</mo><mi>m</mi></mrow></math>"
 }"

Code that converts json to Map:

Map<String, String> variableMap = gson.fromJson(jsonString, new TypeToken<Map<String,String>>(){}.getType());

Error:

[ERROR] The JsonDeserializer StringTypeAdapter failed to deserialize json object {"varA":"<math><mrow><mn>8</mn></mrow></math>","varB":"<math><mrow><mi>m</mi></mrow></math>","ans":"<math><mrow><mn>8</mn><mo>&#8290;</mo><mi>m</mi></mrow></math>"} given the type class java.lang.String

I know it has something to do with the type, but I have indicated that the type will be String explicitly in the type token.

The gson object is declared as follows:

Gson gson = new GsonBuilder().disableHtmlEscaping().create();

You have to escape the quotes that delimit the JSON string values contained within your Java string. In fact your example is not a valid Java program - Java lacks multi-line strings, for starters.

The following snippet runs just fine (angle brackets and the Unicode character turn out to be innocuous):

public static void main(String[] args) {
         String jsonString = "{\"varA\": \"<math><mrow><mn>8</mn></mrow></math>\", \"varB\": \"<math><mrow><mi>m</mi></mrow></math>\", \"ans\": \"<math><mrow><mn>8</mn><mo>&#8290;</mo><mi>m</mi></mrow></math>\"}";
         Map<String, String> variableMap = new Gson().fromJson(jsonString, new TypeToken<Map<String,String>>(){}.getType());
         System.out.println("foo");
    }

It is working when you use Map.class instead of new TypeToken<Map<String,String>>(){}.getType() . See my little example:

Gson gson = new GsonBuilder().disableHtmlEscaping().create();

Map<String, String> map = new HashMap<String, String>();
map.put("varA", "<math><mrow><mn>8</mn></mrow></math>");
map.put("varB", "<math><mrow><mi>m</mi></mrow></math>");
map.put("ans", "<math><mrow><mn>8</mn><mo>&#8290;</mo><mi>m</mi></mrow></math>");

String json = gson.toJson(map);

System.out.println(json);
System.out.println(gson.fromJson(json, Map.class));

It prints:

{
   "varB":"<math><mrow><mi>m</mi></mrow></math>",
   "ans":"<math><mrow><mn>8</mn><mo>&#8290;</mo><mi>m</mi></mrow></math>",
   "varA":"<math><mrow><mn>8</mn></mrow></math>"
}

{varB=<math><mrow><mi>m</mi></mrow></math>, ans=<math><mrow><mn>8</mn><mo>&#8290;</mo><mi>m</mi></mrow></math>, varA=<math><mrow><mn>8</mn></mrow></math>}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM