0

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"

1
  • Try adding escape character \" in your string. I.e. "{\"key\"=\"sample value\"}" Commented Feb 16, 2019 at 6:57

2 Answers 2

1

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\"}";
Sign up to request clarification or add additional context in comments.

1 Comment

Besides that, the key/value separator is colon, not equals. {"key" : "value"}
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.