如何使用Java解析具有每个不同键和值的JSON对象? [英] How to parse the JSON objects with each different key and value, using Java?
问题描述
我知道解析此类JSON的答案:
I know the answer for parsing the JSON of this type:
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food"}
,其中有键值对,键是相同的(如此处的"id"),值是不同的,我们使用for循环来快速解析它.
where there is key value pair, with key being same(like 'id' here) and value differing, and we use a for loop to parse it quickly.
(对于那些想了解如何在JSON上方进行解析的人,请转到此链接:
(For those who'd like to see how to parse above JSON, please go to this link: How to parse nested JSON object using the json library?)
但是,我尝试解析的JSON是一个不同的JSON,对于每个不同的值,它没有像上面一样的"Id"键,但是每个键都是一个具有不同值的新键.下面是示例:
However, the JSON I'm trying to parse is a different one which doesn't have a same key like 'Id' as above for every different value, but every key is a new key with a different value. Below is the example:
{
"disclaimer": "Exchange rates are ...........blah blah",
"license": "Data sourced from various .......blah blah",
"timestamp": 1446886811,
"base": "USD",
"rates": {
"AED": 3.67266,
"AFN": 65.059999,
"ALL": 127.896
.
.
All the currency values.
.
}
}
我不确定如何用所有不同的货币键(如AED和它们的值之类的货币)来解析以上代码,然后将它们弹出到下拉列表中.
I'm not sure how to parse the above one with all different keys of currencies (currency like AED and their value) and pop them up in a drop down list.
我是否必须为每种不同的货币和值对编写新的代码行,或者以某种方式也可以为此使用for循环.
Do I have to write a new line of code for each different currency and value pair or it is in some way possible to use a for loop for this one as well.
如果可以的话,有人可以提供一些行代码吗?
Can someone provide some lines code if possible?
推荐答案
在这种情况下,您可以使用GSON.我将按照汇率打印货币,但是您可以构建其他数据结构(例如地图)并在系统中使用它.
You could use GSON in this case. I will just print the currencies with the according rate but you can build a different data structure(a map for example) and use it in your system.
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
String jsonString = "{\n" +
" \"disclaimer\": \"Exchange rates are ...........blah blah\",\n" +
" \"license\": \"Data sourced from various .......blah blah\",\n" +
" \"timestamp\": 1446886811,\n" +
" \"base\": \"USD\",\n" +
" \"rates\": {\n" +
" \"AED\": 3.67266,\n" +
" \"AFN\": 65.059999,\n" +
" \"ALL\": 127.896\n" +
" }\n" +
"}";
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
for(Map.Entry<String, JsonElement> currency: jsonObject.getAsJsonObject("rates").entrySet()){
System.out.println("Currency "+ currency.getKey()+" has rate " + currency.getValue());
}
}
}
这篇关于如何使用Java解析具有每个不同键和值的JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!