[英]How Parse JSON using GSON WHen object is either JSONObject or JSONArray
[英]Gson is unable to parse a json array string located in an json object AS a JsonArray
内容:
我正在尝试使用gson将以下JSON转换为JAVA POJO
JSON:
{
"task": "findRecords",
"foundRecords": "[1234567, 11234512]",
"logs": "records found [1234567, 11234512]",
"status": "success"
}
POJO类别:
public class JavaPojo {
String task = null;
JsonArray foundRecords = null;
String logs = null;
String status = null;
}
转换逻辑:
JavaPojo pojo = gson.fromJson(jsonString, JavaPojo.class);
其中jsonString
是上述json的字符串表示形式。
问题:
转换逻辑失败
com.google.gson.JsonSyntaxException:预期为com.google.gson.JsonArray,但为com.google.gson.JsonPrimitive
据我了解,gson会将foundRecords
的值解释为纯字符串,而不是将其解析为Array。
现在要解决此问题,我将foundRecords
从JsonArray
修改为String
。 转换成功完成。
有什么线索可以在将foundRecords
类型保留为JsonArray
同时实现转换吗?
注意:
转换后foundRecords
到String
,我试过的字符串值转换foundRecords
到JsonArray
使用GSON而且奇怪的工作。
//This works
//Map json to pojo
JavaPojo pojo = gson.fromJson(jsonString, JavaPojo.class);
//Convert foundRecords into a JsonArray
JsonArray arr = gson.fromJson(pojo.getFoundRecords(), JsonArray.class);
因此,现在我很困惑,如果gson可以将foundFounds的string
类型foundRecords
为JsonArray
那么为什么它不能更早地执行转换呢?
我了解REST API响应不好,并且违反了JSON语法。 解决方案是纠正REST API,但不幸的是,在我的情况下,我无法请求API纠正,因此我在结束时编写了一个util来清理jsonString
。
如果可以帮助任何人,请在此处发布:
/**
* @param malformedArrayKey
* - Name of the key in the JSON object that has a malformed array
* for e.g consider following JSON object having a bad formed array
* <pre>
* {
* "task": "findRecords",
* "foundRecords": "[1234567, 11234512]",
* }
* </pre>
* @param jsonString
* - String representation of the JSON object containing the malformed array
* @return - json string having well formed array against the key {@code malformedArrayKey} supplied
* <pre>
* {
* "task": "findRecords",
* "foundRecords": [1234567, 11234512]
* }
* </pre>
*/
public static String formatMalformedArray(String malformedArrayKey, String jsonString) {
JsonObject jsonObj = gson.fromJson(jsonString, JsonObject.class);
// get the faulty key value
String malformedArrayKeyValue = jsonObj.get(malformedArrayKey)
.getAsString();
// drop it
jsonObj.remove(malformedArrayKey);
// create a array out of the malformed array string
JsonArray jsonArray = gson.fromJson(malformedArrayKeyValue, JsonArray.class);
// add the array back to the object
jsonObj.add(malformedArrayKey, jsonArray);
// now convert it into a well formed json string
return jsonObj.toString();
}
该方法非常基本,但是可以满足我的用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.