微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Java(JSON)读取JSON中嵌套键的值

我是一个来自 Python背景的新Java程序员.我有天气数据正在以JSON的方式收集/返回,其中包含嵌套的键,我不明白在这种情况下如何拉出值.我相信这个问题以前已经被问过了,但是我发誓我已经有Google Googled了很多,我似乎找不到答案.现在我使用json-simple,但是我尝试切换到Jackson,但仍然无法弄清楚如何做到这一点.由于杰克逊/ Gson似乎是最常用的图书馆,我很乐意看到一个使用这些图书馆的例子.以下是数据样本,其次是我迄今为止编写的代码.
{
    "response": {
        "features": {
            "history": 1
        }
     },"history": {
        "date": {
            "pretty": "April 13,2010","year": "2010","mon": "04","mday": "13","hour": "12","min": "00","tzname": "America/Los_Angeles"
        },...
    }
}

功能

public class Tester {

    public static void main(String args[]) throws MalformedURLException,IOException,ParseException {
        WundergroundAPI wu =  new WundergroundAPI("*******60fedd095");

        JSONObject json = wu.historical("San_Francisco","CA","20100413");

        System.out.println(json.toString());
        System.out.println();
        //This only returns 1 level. Further .get() calls throw an exception
        System.out.println(json.get("history"));
    }
}

函数“historical”调用一个返回JSONObject的函数

public static JSONObject readJsonFromUrl(URL url) throws MalformedURLException,ParseException {

    InputStream inputStream = url.openStream();

    try {
        JSONParser parser = new JSONParser();
        BufferedReader buffReader = new BufferedReader(new InputStreamReader(inputStream,Charset.forName("UTF-8")));

        String jsonText = readAll(buffReader);
        JSONObject json = (JSONObject) parser.parse(jsonText);
        return json;
    } finally {
        inputStream.close();
    }
}

解决方法

使用杰克逊的树模型(JsonNode),您有两个“文字”访问器方法(‘get’),它为缺失值返回null,“safe”访问器(‘path’)允许您遍历“丢失”节点.所以,例如:
JsonNode root = mapper.readTree(inputSource);
int h = root.path("response").path("history").getValueAsInt();

这将返回给定路径上的值,或者如果路径丢失,则为0(认值)

但是更方便的是你可以使用JSON指针表达式:

int h = root.at("/response/history").getValueAsInt();

还有其他方法,通常更实用的模拟您的结构作为普通Java对象(PO​​JO)更方便.
您的内容可能适合:

public class Wrapper {
  public Response response;
} 
public class Response {
  public Map<String,Integer> features; // or maybe Map<String,Object>
  public List<HistoryItem> history;
}
public class HistoryItem {
  public MyDate date; // or just Map<String,String>
  // ... and so forth
}

如果是这样,您将像任何Java对象一样遍历结果对象.

原文地址:https://www.jb51.cc/java/124645.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐