无法转换包含少量元素且内部有数组的 JSON 字符串。 在用户界面上,我需要将数组提供给引导表。
JSON 字符串:
{
"IsOperationSuccessful": true,
"IsResult": true,
"StatusCode": "OK",
"Response": [{
"PlaylistCreatedBy": "XYZ",
"PlaylistCreatedOn": "10/10/2019 14:10",
"PlaylistDisplayTitle": "blah",
"PlaylistId": 101,
"PlaylistScheduledReleaseTime": "10/10/2019 14:10"
}, {
"PlaylistCreatedBy": "HHJK",
"PlaylistCreatedOn": "10/10/2019 14:10",
"PlaylistDisplayTitle": "blah blah",
"PlaylistId": 102,
"PlaylistScheduledReleaseTime": "10/10/2019 14:10"
}, {
"PlaylistCreatedBy": "HJHJ",
"PlaylistCreatedOn": "10/10/2019 14:10",
"PlaylistDisplayTitle": "UIUI",
"PlaylistId": 103,
"PlaylistScheduledReleaseTime": "10/10/2019 14:10"
}, {
"PlaylistCreatedBy": "KJK",
"PlaylistCreatedOn": "10/10/2019 14:10",
"PlaylistDisplayTitle": "kkj",
"PlaylistId": 104,
"PlaylistScheduledReleaseTime": "10/10/2019 14:10"
}],
"Total": 4
}
到目前为止我添加的代码:
PreRecordedCall morningCallResponse = new PreRecordedCall();
JSONArray playListinfo = null;
String testResponse = "//Json Goes here "
JSONObject finalJson = new JSONObject();
finalJson.put("testResponse", testResponse);
Gson gson = new Gson();
morningCallResponse = gson.fromJson(testResponse,
PreRecordedCall.class);
playListinfo = morningCallResponse.getPreRecordplayListInformation();
最佳答案
一种方法是创建 2 个 POJO(如 Response
和 PreRecordedCall
),如下所示。
Response
用于具有键“Response”和 PreRecordedCall
的 JSON 数组适用于整个 JSON 对象。关键是用List<Response>
存储 JSON 数组。
顺便说一句,为了遵循 POJO 中变量的命名规则,我使用了小驼峰命名法 @SerializedName
用于对象名称映射。
类 react
static class Response {
@SerializedName("PlaylistCreatedBy")
private String playlistCreatedBy;
@SerializedName("PlaylistCreatedOn")
private String playlistCreatedOn;
@SerializedName("PlaylistDisplayTitle")
private String playlistDisplayTitle;
@SerializedName("PlaylistId")
private int playlistId;
@SerializedName("PlaylistScheduledReleaseTime")
private String playlistScheduledReleaseTime;
//general getters and setters
}
PreRecordedCall 类
static class PreRecordedCall {
@SerializedName("IsOperationSuccessful")
private Boolean isOperationSuccessful;
@SerializedName("IsResult")
private Boolean isResult;
@SerializedName("StatusCode")
private String statusCode;
@SerializedName("Response")
private List<Response> response;
@SerializedName("Total")
private int total;
//general getters and setters
}
然后您可以简单地将 JSON 字符串转换为预定义的 POJO,如下所示:
Gson gson = new Gson();
PreRecordedCall preRecordedCall = gson.fromJson(testResponse, PreRecordedCall.class);
System.out.println(preRecordedCall.getResponse().size());
控制台输出
4
如果您使用 Jackson
作为您的 JSON 解析器,更改 @SerializedName
至@JsonProperty
您可以通过以下代码片段获得相同的结果。
ObjectMapper mapper = new ObjectMapper();
PreRecordedCall preRecordedCall = mapper.readValue(testResponse, PreRecordedCall.class);
System.out.println(preRecordedCall.getResponse().size());
关于java - 如何将包含数组的 JSON 转换为 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58441244/