gpt4 book ai didi

java - GSON。如何将json对象转换为json数组?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:53:55 26 4
gpt4 key购买 nike

现在我从 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com