简体   繁体   中英

Error Parsing JSON String to JSONObject in Java

I have an application that stores this JSON String :

String message ="{\\"uid\\":\\"1\\",\\"streetName\\":\\"road\\",\\"city\\":\\"London\\",\\"speedLimit\\":20}"

Now I want to parse it back to a JSON Object, In order to do so I have this line:

    JsonObject object = new JsonParser().parse(message).getAsJsonObject();

I am using Gson Library to parse it and use it as a JSON Object. However, I am getting this exception :

com.google.gson.stream.MalformedJsonException: Expected name at line 1 column 2 path $.

Update 1

I have tried this

String message = "{"uid":"1","streetName":"road","city":"London","speedLimit":20}";
JSONObject object = new JSONObject(message);

Now I get this exception:

Unterminated string at character 28 of {"uid":"1","streetName":"roa

I have tried lots of workarounds from multiple threads on StackOverflow but nothing is working and I have no idea why ?

You can Directly cast it to the JSONObject,

JSONObject response = new JSONObject();
String str =  "{\"uid\":\"1\",\"streetName\":\"road\",\"city\":\"London\",\"speedLimit\":20}";
response = new JSONObject(str);

Now the string response has casted as Json response.

you code is fine and should work

please check on the import of the JsonParser in your java file (should be com.google.gson.JsonParser)

let know on the Gson version if the JsonParser is not the issue

your code should work, may be you need to check the dependencies as mentioned before.

I am using this dependency https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.0

here is an sscce that work https://github.com/SalehAly/test-gson

码

I found my problem.

The String I was processing was malformed for the source. Fixing the string was the answer in here. Nothing was wrong with how I parsed the string.

Thanks for all the answers and the help.

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