有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用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是一个不同的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循环

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


共 (1) 个答案

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