Java 8的简单JSON值解析 [英] Simple JSON value parsing for Java 8

查看:820
本文介绍了Java 8的简单JSON值解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是Java 8,尽管我已经在我的类路径上有了Jackson和Jettison(作为依赖项).

Java 8 here though I have Jackson and Jettison on my classpath already (as dependencies).

为我提供了以下JSON字符串(作为示例):

I am being given the following string of JSON (as an example):

{
    "widgets": {
        "email": "someone@example.com",
        "maxSize": 50
    },
    "environments": {
        "LOCAL": {
            "maxSize": "40"
        },
        "DEV": {
            "maxSize": "100"
        }
    },
    "fruits": [
        "apples",
        "oranges"
    ]
}

在运行时,这些字段的值将不同.

At runtime the values of the fields will be different.

我只是想从该字符串中读取environments/DEV/maxSize的值;我可以编写出最简单的代码来提取该值的方法是什么?

I am just trying to read the value of environments/DEV/maxSize from this string; what is the simplest code I can write to extract this value?

理想情况下,可能对此类型的东西提供了Java 8的内置支持,但是如果需要注意的话,我希望Jackson或Jettison都具有此功能,而不必在我的项目中添加新的jar/依赖项.最坏的情况就是使用某种正则表达式去除我想的值...

Ideally there might be some built in Java 8 support for this type of thing, but if note, I hopefully either Jackson or Jettison ship with this capability without having to add a new jar/dependency to my project. Worst case scenario would be just using some kind of regex to strip out the value I suppose...

有什么想法吗?

推荐答案

一个简单的选择是使用 JsonPath .可以使用$.environments.DEV.maxSize:

A simple option would be to use JsonPath. Nested properties can be pulled using a path specifier like $.environments.DEV.maxSize:

long maxSize = JsonPath.parse(json).read("$.environments.DEV.maxSize", Long.class);

使用Jackson,可以通过JsonNode完成此操作:

With Jackson, this can be done either with JsonNode:

long maxSize = new ObjectMapper()
    .readTree(json)
    .get("environments").get("DEV").get("maxSize").asLong();

或者如果您有一个表示数据的类,则可以反序列化为该数据:

Or if you have a class that represents the data, you can deserialize to that:

MyConfig myConfig = new ObjectMapper().readValue(json, MyConfig.class);
long maxSize = myConfig.getEnvironments().get(Environment.DEV).getMaxSize();

这篇关于Java 8的简单JSON值解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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