GSON. 如何将JSON对象转换为JSON数组?

10

现在我从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来实现这个?


如果我理解你的问题正确,你可能会收到一个JsonObject或JsonArray。你可以调用getAsJsonObject()方法,如果失败了,就调用getAsJsonArray()。 - Fustigador
或者使用 isJsonObject() 方法,根据结果调用 getAsJsonObject() 或 getAsJsonArray()。 - Fustigador
7个回答

4
希望这部分代码能帮到你:
    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());

3

GSON使用POJO类将JSON解析为Java对象。

创建一个Java类,其中包含与JSON对象键相同的变量名称和数据类型。我认为您收到的JSON格式不正确。

Class SupplyPrice{
 double CAD;
 double CHF;
 double TRY
}

Class SupplyPriceContainer{
 ArrayList<SupplyPrice> supplyPrice;
}

你的JSON应该是这样的:
 {
    "CAD": 78,
    "CHF": 54600.78,
    "USD": 20735.52
 }



{
    "supplyPrice": [{
        "CAD": 78,
        "CHF": 0,
        "USD": 0
    }, {
        "CAD": 0,
        "CHF": 54600.00,
        "USD": 0
    }, {
        "CAD": 0,
        "CHF": 0,
        "USD": 20735.52
    }]
 }

然后,您可以使用GSON的`fromJson(String pJson, Class pClassType)`将其转换为Java对象。
  Gson gson = new Gson()
  ArrayList<SupplyPrice> suplyPrices = gson.fromJson(pJsonString, SupplyPrice.class);

现在你可以使用ArrayList获取数据。

2
您需要迭代supplyPrice对象的所有键,然后使用该键值创建一个新的JSONArray,然后将新数组分配给supplyPrice键。
JSONObject changeSupplyPrice(JSONObject JSONObj){
    try {
        JSONObject supplyPrice =JSONObj.getJSONObject("supplyPrice");
        JSONArray supplyPriceArray = new JSONArray();
        Iterator<?> keys = supplyPrice.keys();

        while( keys.hasNext() ) {
            String key = (String)keys.next();
            Log.e("JSON Array key",key);
            supplyPriceArray.put(new JSONObject("{"+key+":"+supplyPrice.getString(key)+"}"));

        }
        JSONObj.put("supplyPrice", supplyPriceArray);
        return JSONObj;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

然后在你想要的位置调用该函数。
try {
        JSONObject JSONObj = new JSONObject("{'taxes': [],'name': 'Laboriosam iusto eum','requiresShipping': false,  'taxable': true,  'sku': 'QBA84J18832',  'product': 12, 'supplyPrice': {    'CAD': 78,   'CHF': 54600.78,    'USD': 20735.52  }}");
        JSONObj = changeSupplyPrice(JSONObj);
        Log.e("Return JSON Object",JSONObj.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

1
感谢Rohit Patil!我根据我的情况修改了他的代码,现在它可以工作了!
private JSONObject modifyPrices(JSONObject JSONObj) {
    try {
        JSONObject supplyPrice = JSONObj.getJSONObject("supplyPrice");
        JSONArray supplyPriceArray = new JSONArray();
        Iterator<?> keys = supplyPrice.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            String value = supplyPrice.getString(key);
            supplyPriceArray.put(new JSONObject("{\"name\":" + key + ",\"value\":" + value + "}"));
        }
        JSONObj.put("supplyPrice", supplyPriceArray);
        return JSONObj;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

0

看一眼这个.. 可能会对你有帮助。

 JSONObject json= json.getJSONObject("supplyPrice");
    Iterator i = json.keys();
    JSONArray jsonArray = new JSONArray();

    while (i.hasNext()){
        String key = (String) i.next();
        jsonArray.put(json.get(key));

0

您可以直接将其转换为HashMap或TreeMap,然后遍历您的映射以获取所有键。

这将是实现您想要的最简单的方法。


0

我们只需要一行代码就可以将jsonObjects转换为数组(不是jsonArrays,但在将其转换为arrayList后,您也可以轻松创建jsonArray。)

fun <LIST_TYPE>jsonObjectToArray(jsonObject : JsonObject,listTypeClass : Class<LIST_TYPE>) = arrayListOf<LIST_TYPE>().apply { jsonObject.keySet().forEach { this.add(Gson().fromJson(jsonObject.get(it).toString(),listTypeClass))}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接