Reputation: 2449
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>⁢</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>⁢</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();
Upvotes: 1
Views: 1263
Reputation: 38665
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>⁢</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>⁢</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>⁢</mo><mi>m</mi></mrow></math>, varA=<math><mrow><mn>8</mn></mrow></math>}
Upvotes: 1
Reputation: 5242
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>⁢</mo><mi>m</mi></mrow></math>\"}";
Map<String, String> variableMap = new Gson().fromJson(jsonString, new TypeToken<Map<String,String>>(){}.getType());
System.out.println("foo");
}
Upvotes: 2