[英]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.