pvn
pvn

Reputation: 2126

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"

Upvotes: 0

Views: 144

Answers (2)

DEV-Jacol
DEV-Jacol

Reputation: 607

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

Upvotes: 0

frogatto
frogatto

Reputation: 29287

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\"}";

Upvotes: 1

Related Questions