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 ?
答案 0 :(得分:0)
您可以直接将其强制转换为JSONObject,
JSONObject response = new JSONObject();
String str = "{\"uid\":\"1\",\"streetName\":\"road\",\"city\":\"London\",\"speedLimit\":20}";
response = new JSONObject(str);
现在字符串响应已经作为Json响应生成。
答案 1 :(得分:0)
您的代码很好,应该可以使用
请检查java文件中JsonParser的导入(应该是com.google.gson.JsonParser)
如果JsonParser不是问题,请告知Gson版本
答案 2 :(得分:0)
您的代码应该可以运行,可能需要检查之前提到的依赖项。
我正在使用此依赖关系https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.0
答案 3 :(得分:0)
我发现了我的问题。
我正在处理的字符串格式错误。修复字符串就是这里的答案。我如何解析字符串没有错。
感谢所有答案和帮助。