使用Java读取JSON中的嵌套键的值(Jackson) [英] Reading value of nested key in JSON with Java (Jackson)

查看:259
本文介绍了使用Java读取JSON中的嵌套键的值(Jackson)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是来自Python背景的新Java程序员。我有收集/返回的天气数据作为JSON与嵌套键,我不明白如何在这种情况下拉出值。我确信这个问题之前已经被问过了,但我发誓我已经Google搜索了很多东西,我似乎无法找到答案。现在我正在使用json-simple,但我尝试切换到Jackson,但仍然无法弄清楚如何做到这一点。由于杰克逊/格森似乎是最常用的库,我很乐意看到使用其中一个库的例子。下面是一个数据样本,后面是我迄今为止编写的代码。

  {
response:{
features:{
history :
date:{
pretty:2010年4月13日,

year:2010,
mon:04,
mday:13,
hour:12,
min :00,
tzname:America / Los_Angeles
},
...
}
}


$ b

主函数

  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();
//这只返回1级。进一步.get()调用抛出一个异常
System.out.println(json.get(history));





$ b $ p

函数'historical'调用另一个函数,返回一个JSONObject

  public static JSONObject readJsonFromUrl(URL url)抛出MalformedURLException,IOException,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);
返回json;
} finally {
inputStream.close();
}
}


解决方案

杰克逊的树模型( JsonNode ),你有两个字面存取方法('get'),它返回 null 对于缺失的值和安全访问器('路径'),它们允许您遍历缺少节点。例如:

  JsonNode root = mapper.readTree(inputSource); 
int h = root.path(response)。path(history)。getValueAsInt();

这会返回给定路径的值,或者如果缺少路径,则为0(默认值)



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

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

还有其他一些方法,通常将结构建模为Plain Old Java对象(PO​​JO)。
您的内容可能符合以下要求:

  public class Wrapper {
public response response;
}
public class Response {
public Map< String,Integer>特征; //或者也许Map< String,Object>
public List< HistoryItem>历史;
}
public class HistoryItem {
public MyDate date; //或只是映射< String,String>
// ...等等
}

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


I'm a new Java programmer coming from a background in Python. I have weather data that's being collected/returned as a JSON with nested keys in it, and I don't understand how pull the values out in this situation. I'm sure this question has been asked before, but I swear I've Googled a great deal and I can't seem to find an answer. Right now I'm using json-simple, but I tried switching to Jackson and still couldn't figure out how to do this. Since Jackson/Gson seem to be the most used libraries, I'd would love to see an example using one of those libraries. Below is a sample of the data, followed by the code I've written so far.

{
    "response": {
        "features": {
            "history": 1
        }
     },
    "history": {
        "date": {
            "pretty": "April 13, 2010",
            "year": "2010",
            "mon": "04",
            "mday": "13",
            "hour": "12",
            "min": "00",
            "tzname": "America/Los_Angeles"
        },
        ...
    }
}

Main function

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

The function 'historical' calls another function that returns a JSONObject

public static JSONObject readJsonFromUrl(URL url) throws MalformedURLException, IOException, 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();
    }
}

解决方案

With Jackson's tree model (JsonNode), you have both "literal" accessor methods ('get'), which returns null for missing value, and "safe" accessors ('path'), which allow you to traverse "missing" nodes. So, for example:

JsonNode root = mapper.readTree(inputSource);
int h = root.path("response").path("history").getValueAsInt();

which would return the value at given path, or, if path is missing, 0 (default value)

But more conveniently, you can just use JSON pointer expression:

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

There are other ways too, and often it is more convenient to actually model your structure as Plain Old Java Object (POJO). Your content could fit something like:

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
}

and if so, you would traverse resulting objects just like any Java objects.

这篇关于使用Java读取JSON中的嵌套键的值(Jackson)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆