现在我从 API 获取这个 JSON:
{"supplyPrice": {
"CAD": 78,
"CHF": 54600.78,
"USD": 20735.52
}}
但是价格是动态的,这就是为什么我需要这种形式的 JSON
{
"supplyPrice": [
{
"name": "CAD",
"value": "78"
},
{
"name": "TRY",
"value": "34961.94"
},
{
"name": "CHF",
"value": "54600.78"
},
{
"name": "USD",
"value": "20735.52"
}
]
}
如何使用 GSON 做到这一点?
最佳答案
希望这部分代码对您有所帮助:
String json = "{\"supplyPrice\": {\n" +
" \"CAD\": 78,\n" +
" \"CHF\": 54600.78,\n" +
" \"USD\": 20735.52\n" +
" }}";
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
JsonObject supplyPrice = jsonObject.get("supplyPrice").getAsJsonObject();
Type type = new TypeToken<HashMap<String, Double>>() {
}.getType();
HashMap<String, Double> parsedJson = gson.fromJson(supplyPrice, type);
JsonArray jsonArray = new JsonArray();
for(String key : parsedJson.keySet()) {
JsonObject jo = new JsonObject();
jo.addProperty("name", key);
jo.addProperty("value", parsedJson.get(key));
jsonArray.add(jo);
}
JsonObject result = new JsonObject();
result.add("supplyPrice", jsonArray.getAsJsonArray());
关于java - GSON。如何将json对象转换为json数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35083609/