如何使用Java解析具有每个不同键和值的JSON对象?

时间:2015-11-07 09:43:08

标签: java json

我知道解析这种类型的JSON的答案:

                    { "id": "1001", "type": "Regular" },
                    { "id": "1002", "type": "Chocolate" },
                    { "id": "1003", "type": "Blueberry" },
                    { "id": "1004", "type": "Devil's Food"}

其中有键值对,键相同(如'id'在这里)和值不同,我们使用for循环快速解析它。

(对于那些想要了解如何解析JSON之上的人,请转到此链接:How to parse nested JSON object using the json library?

但是,我试图解析的JSON是一个不同的,它对于每个不同的值没有像上面的“Id”相同的键,但是每个键都是具有不同值的新键。以下是示例:

{
  "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等货币及其价值)解析上述货币,并在下拉列表中弹出。

我是否必须为每个不同的货币和价值对编写新的代码行,或者以某种方式为这个代码使用for循环。

如果有可能,某人可以提供一些行代码吗?

2 个答案:

答案 0 :(得分:1)

你可以使用org.json来做这件事。

E.g:

JSONObject json = new JSONObject("<jsonString>");
 Iterator<String> keys = json.keys();

    while (keys.hasNext()) {
        String key = keys.next();
        System.out.println("Key :" + key + "  Value :" + json.get(key));
    }

答案 1 :(得分:1)

在这种情况下你可以使用GSON。我只会按照相应的费率打印货币,但您可以构建不同的数据结构(例如地图)并在系统中使用它。

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