如何解析未定义长度的剩余对象响应
How to parse undefined length rest object response
我有一个 API 它的端点之一 returns 这个 json 对象(来自这个 API)
问题是,它不是数组!它是一个单一的简单对象。但是,如果您单击 link 并且还认为“此文档应该是什么”:“BASE”实际上代表一种货币,如“USD”。所以最后我们有一个 Currency:Information 对的映射。
如何使用 Gson 将其解析为 java 对象?哪里有未知数量的“BASE”:“INFO”映射? (密钥基本上是未知的)
{
"BASE": {
"commoditymarketvalue": 0,
"futuremarketvalue": 0,
"settledcash": 0,
"exchangerate": 0,
"sessionid": 0,
"cashbalance": 0,
"corporatebondsmarketvalue": 0,
"warrantsmarketvalue": 0,
"netliquidationvalue": 0,
"interest": 0,
"unrealizedpnl": 0,
"stockmarketvalue": 0,
"moneyfunds": 0,
"currency": "string",
"realizedpnl": 0,
"funds": 0,
"acctcode": "string",
"issueroptionsmarketvalue": 0,
"key": "string",
"timestamp": 0,
"severity": 0
}
}
是否要将其反序列化为 String 映射到某些 pojo?喜欢这里:How to de-serialize a Map<String, Object> with GSON
?
(审核后编辑)
来自 url 的解决方案:
static class PersonData {
int age;
String surname;
public String toString() {
return "[age = " + age + ", surname = " + surname + "]";
}
}
public static void main(String[] args) {
String json = "{\"Thomas\": {\"age\": 32,\"surname\": \"Scott\"},\"Andy\": {\"age\": 25,\"surname\": \"Miller\"}}";
System.out.println(json);
Gson gson = new Gson();
Map<String, PersonData> decoded = gson.fromJson(json, new TypeToken<Map<String, PersonData>>(){}.getType());
System.out.println(decoded);
}
如果你想更灵活,你可以将它反序列化为Map.class并随意遍历它。
我有一个 API 它的端点之一 returns 这个 json 对象(来自这个 API)
问题是,它不是数组!它是一个单一的简单对象。但是,如果您单击 link 并且还认为“此文档应该是什么”:“BASE”实际上代表一种货币,如“USD”。所以最后我们有一个 Currency:Information 对的映射。
如何使用 Gson 将其解析为 java 对象?哪里有未知数量的“BASE”:“INFO”映射? (密钥基本上是未知的)
{
"BASE": {
"commoditymarketvalue": 0,
"futuremarketvalue": 0,
"settledcash": 0,
"exchangerate": 0,
"sessionid": 0,
"cashbalance": 0,
"corporatebondsmarketvalue": 0,
"warrantsmarketvalue": 0,
"netliquidationvalue": 0,
"interest": 0,
"unrealizedpnl": 0,
"stockmarketvalue": 0,
"moneyfunds": 0,
"currency": "string",
"realizedpnl": 0,
"funds": 0,
"acctcode": "string",
"issueroptionsmarketvalue": 0,
"key": "string",
"timestamp": 0,
"severity": 0
}
}
是否要将其反序列化为 String 映射到某些 pojo?喜欢这里:How to de-serialize a Map<String, Object> with GSON ?
(审核后编辑) 来自 url 的解决方案:
static class PersonData {
int age;
String surname;
public String toString() {
return "[age = " + age + ", surname = " + surname + "]";
}
}
public static void main(String[] args) {
String json = "{\"Thomas\": {\"age\": 32,\"surname\": \"Scott\"},\"Andy\": {\"age\": 25,\"surname\": \"Miller\"}}";
System.out.println(json);
Gson gson = new Gson();
Map<String, PersonData> decoded = gson.fromJson(json, new TypeToken<Map<String, PersonData>>(){}.getType());
System.out.println(decoded);
}
如果你想更灵活,你可以将它反序列化为Map.class并随意遍历它。