简体   繁体   English

在Java中将JSON字符串解析为JSONObject时出错

[英]Error Parsing JSON String to JSONObject in Java

I have an application that stores this JSON String : 我有一个存储此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: 现在,我想将其解析回JSON对象,为此,我有这行代码:

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

I am using Gson Library to parse it and use it as a JSON Object. 我正在使用Gson库来解析它,并将其用作JSON对象。 However, I am getting this exception : 但是,我收到此异常:

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

Update 1 更新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 ? 我已经从StackOverflow上的多个线程尝试了许多变通办法,但是没有任何效果,我也不知道为什么?

You can Directly cast it to the JSONObject, 您可以将其直接转换为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. 现在,字符串响应已转换为Json响应。

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) 请检查Java文件中JsonParser的导入(应为com.google.gson.JsonParser)

let know on the Gson version if the JsonParser is not the issue 如果不是JsonParser,请在Gson版本上告知

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 我正在使用此依赖项https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.0

here is an sscce that work https://github.com/SalehAly/test-gson 这是一个可以工作的sscce 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. 感谢您提供所有答案和帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM