【发布时间】:2020-04-11 23:25:25
【问题描述】:
是否可以解析对 POJO 的 JSON 响应,即使响应只发回行和列?
我从一个 API 得到这个响应:
{
"rows": [
[
"FIRST NATIONAL BANK OF OMAHA",
36644,
"COM",
44527,
198809,
"SH",
-1.5631,
"Put",
"2019-09-30"
],
[
"WAYNE HUMMER INVESTMENTS L.L.C.",
49096,
"COM",
17975,
90817,
"SH",
2.8971,
"Put",
"2019-06-30"
]
],
"columns": [
"Institution Name",
"Institution CIK",
"Class of Security Held",
"Value of Security Held",
"Volume of Security Held",
"Type of Security Held",
"Quarterly Change in Security Held",
"Put/Call",
"Report Date"
]
}
这是我正在使用的代码,为简洁起见,用于连接到 API 并获取我使用 Gson 通过反序列化器类传递的 JSON 响应:
public static void requestResponse(){
URL apiURL = new URL("http://apilink.com/api/getSomething.json?T=gnbuweiogh9y89234y&symbol=GOOG");
String readLine = null;
HttpConnection apiConnection = (HttpConnection) apiURL.openConnection();
apiConnection.setRequestMethod("GET");
int responseCode = apiConnection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(apiConnection.getInputStream()));
StringBuffer response = new StringBuffer();
while((readLine = in.readLine()) != null) {
response.append(readLine);
}
in.close();
String jsonResponse = response.toString();
Deserializer deSerializer = new Gson().fromJson(jsonResponse, Deserializer .class);
List<String> columns = deSerializer.getColumns;
// Do something with the data
}
}
这是我做的反序列化类:
public class deSerializer {
@SerializedName("rows")
@Expose
private List<List<String>> rows = null;
@SerializedName("columns")
@Expose
private List<String> columns = null;
public List<List<String>> getRows() {
return rows;
}
public void setRows(List<List<String>> rows) {
this.rows = rows;
}
public List<String> getColumns() {
return columns;
}
public void setColumns(List<String> columns) {
this.columns = columns;
}
}
我希望 JSON 响应采用这种格式,这会使序列化更简单:
{
"data": [{
"Institution Name": "FIRST NATIONAL BANK OF OMAHA",
"Institution CIK": 36644,
"Class of Security Held": "COM",
"Value of Security Held": 44527
} ]
}
很抱歉,这篇文章很长,但是反序列化对 POJO 的响应的最佳方法是什么?
非常感谢。
【问题讨论】: