繁体   English   中英

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

[英]Error Parsing JSON String to JSONObject in Java

我有一个存储此JSON String的应用程序:

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

现在,我想将其解析回JSON对象,为此,我有这行代码:

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

我正在使用Gson库来解析它,并将其用作JSON对象。 但是,我收到此异常:

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

更新1

我已经试过了

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

现在我得到这个异常:

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

我已经从StackOverflow上的多个线程尝试了许多变通办法,但是没有任何效果,我也不知道为什么?

您可以将其直接转换为JSONObject,

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

现在,字符串响应已转换为Json响应。

您的代码很好,应该可以工作

请检查Java文件中JsonParser的导入(应为com.google.gson.JsonParser)

如果不是JsonParser,请在Gson版本上告知

您的代码应该可以工作,可能是您需要如上所述检查依赖项。

我正在使用此依赖项https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.0

这是一个可以工作的sscce https://github.com/SalehAly/test-gson

码

我发现了问题。

我正在处理的字符串的来源格式不正确。 解决字符串是这里的答案。 我解析字符串的方式没错。

感谢您提供所有答案和帮助。

暂无
暂无

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

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