java GSON。如何将json对象转换为json数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35083609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
GSON. How to convert json object to json array?
提问by Joe Richard
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 做到这一点?
采纳答案by Joe Richard
Thanks to Rohit Patil! I modified his code to my situation and it works!
感谢罗希特·帕蒂尔!我根据我的情况修改了他的代码并且它有效!
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;
}
回答by Rohit Patil
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 对象的所有键,并使用该键值创建新的 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();
}
回答by David Rauca
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());
回答by bpr10
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 来获取数据。
回答by Satish Karuturi
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));
回答by steve moretz
We are only one line of code away from converting jsonObjects to arrays(Not jsonArrays but after making it a arrayList you can create jsonArray too,easily.)
我们只需一行代码即可将 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))}}
回答by peeyush pathak
You can directly convert it to an HashMap or TreeMap
then navigate your map for all the keys.
您可以直接将其转换为一个,HashMap or TreeMap
然后为所有键导航您的地图。
This will be simplest way to achieve what you want.
这将是实现您想要的最简单的方法。