1 回答
TA贡献1890条经验 获得超9个赞
我了解 REST API 响应不好并且违反了 JSON 语法。解决方案是更正 REST API,但不幸的是,在我的场景中,我无法请求 API 更正,所以我在最后编写了一个实用程序来清理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();
}
该方法非常基本,但可以满足我的用例。
添加回答
举报