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

时间:2022-01-20 13:41:20

Now I am getting this JSON from API:

现在我从API获取此JSON:

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

But prices are dynamic, that's why I need JSON in this form

但价格是动态的,这就是我需要这种形式的JSON的原因

{
  "supplyPrice": [
    {
      "name": "CAD",
      "value": "78"
    },
    {
      "name": "TRY",
      "value": "34961.94"
    },
    {
      "name": "CHF",
      "value": "54600.78"
    },
    {
      "name": "USD",
      "value": "20735.52"
    }
  ]
}

How to do this using GSON?

如何使用GSON做到这一点?

6 个解决方案

#1


2  

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<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());

#2


1  

You need to iterate all keys of supplyPrice object, and create New JSONArray using that key value then assign new array to supplyPrice key

您需要迭代supplyPrice对象的所有键,并使用该键值创建New 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;
}

then call the function where you want

然后调用你想要的功能

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();
    }

#3


1  

GSON uses POJO classes to parse JSON into java objects.

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

Create A java class containing variables with names and datatype same as keys of JSON object. I think the JSON you are getting is not in the right format.

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

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

Class SupplyPriceContainer{
 ArrayList<SupplyPrice> supplyPrice;
}

And your JSON should be

你的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
    }]
 }

Then you can Use GSON's `fromJson(String pJson, Class pClassType) to convert to JAVA object

然后你可以使用GSON的`fromJson(String pJson,Class pClassType)转换为JAVA对象

  Gson gson = new Gson()
  ArrayList<SupplyPrice> suplyPrices = gson.fromJson(pJsonString, SupplyPrice.class);

Now you can use the arraylist to get the data.

现在您可以使用arraylist来获取数据。

#4


0  

You can directly convert it to an HashMap or TreeMap then navigate your map for all the keys.

您可以直接将其转换为HashMap或TreeMap,然后在地图中导航所有键。

This will be simplest way to achieve what you want.

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

#5


0  

Thanks to Rohit Patil! I modified his code to my situation and it works!

感谢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;
}

#6


0  

Once look at this.. may help you.

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

 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));

#1


2  

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<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());

#2


1  

You need to iterate all keys of supplyPrice object, and create New JSONArray using that key value then assign new array to supplyPrice key

您需要迭代supplyPrice对象的所有键,并使用该键值创建New 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;
}

then call the function where you want

然后调用你想要的功能

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();
    }

#3


1  

GSON uses POJO classes to parse JSON into java objects.

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

Create A java class containing variables with names and datatype same as keys of JSON object. I think the JSON you are getting is not in the right format.

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

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

Class SupplyPriceContainer{
 ArrayList<SupplyPrice> supplyPrice;
}

And your JSON should be

你的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
    }]
 }

Then you can Use GSON's `fromJson(String pJson, Class pClassType) to convert to JAVA object

然后你可以使用GSON的`fromJson(String pJson,Class pClassType)转换为JAVA对象

  Gson gson = new Gson()
  ArrayList<SupplyPrice> suplyPrices = gson.fromJson(pJsonString, SupplyPrice.class);

Now you can use the arraylist to get the data.

现在您可以使用arraylist来获取数据。

#4


0  

You can directly convert it to an HashMap or TreeMap then navigate your map for all the keys.

您可以直接将其转换为HashMap或TreeMap,然后在地图中导航所有键。

This will be simplest way to achieve what you want.

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

#5


0  

Thanks to Rohit Patil! I modified his code to my situation and it works!

感谢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;
}

#6


0  

Once look at this.. may help you.

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

 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));