简体   繁体   中英

GSON parsing error while parsing String to hashmap

I am trying to parse a string using Gson

String str = "{key=sample value}";
new Gson().fromJson(str, HashMap.class())

I am getting a JSONSyntax exception for this. If I change the string to "{key=samplevalue}" it works fine(removed space). Can anyone please explain. What should be done so that I get hashmap as "key" = "sample value"

In JSON specification , both key and value (if it's of type string) must be double quoted. So, in your example the valid JSON is:

{"key":"sample value"}

which in Java, " should be escaped:

String str = "{\"key\":\"sample value\"}";

your code does not compile

you would have to replace class() with class it would be necessary to improve the JSON format it would be necessary to improve the JSON format by adding quotes and an apostrophe

String str = "{'key'='sample value'}";
HashMap hashMap = new Gson().fromJson(str, HashMap.class);
System.out.println(hashMap);  /// ===> {key=sample value}

or

String str = "{\"key\":\"sample value\"}";;
HashMap hashMap = new Gson().fromJson(str, HashMap.class);
System.out.println(hashMap);  /// ===> {key=sample value}

now is working

https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson

http://tutorials.jenkov.com/java-json/gson.html#parsing-json-into-java-objects

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