GSON. How to convert json object to json array?

前端 未结 7 1869
没有蜡笔的小新
没有蜡笔的小新 2021-02-08 15:20

Now I am getting this JSON from API:

{\"supplyPrice\": {
        \"CAD\": 78,
        \"CHF\": 54600.78,
        \"USD\": 20735.52
      }}

But

7条回答
  •  清歌不尽
    2021-02-08 16:14

    Hope this part of code to help you:

        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>() {
        }.getType();
        HashMap 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());
    

提交回复
热议问题