在java中查询JSONObject [英] Query a JSONObject in java

查看:570
本文介绍了在java中查询JSONObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有某个地方存在能够查询JSONObject的java librery。在更深入的情况下,我正在寻找类似于:

  String json ={data:{ data2:{value:'hello'}}}; 

...
//不知何故,我们设法将json转换为jsonObject
...

String result = jsonObject.getAsString(data。 data2.value);

System.out.println(result);

我希望得到hello作为输出。


$ b $到目前为止,我发现的最快捷的方式是使用Gson:
$ b

  jsonObject。 。getAsJsonObject( 数据)getAsJsonObject()得到( DATA2)getAsJsonObject( 值)符getAsString()。; 

写入和读取并不容易。有什么更快的吗?

解决方案

首先,我会建议考虑JSON对象绑定。



但是如果你得到了任意的JSON对象,并且你想按照你描述的方式处理它们,我会建议将 Jackson JSON处理器以及Apache的 Commons Beanutils



这个想法如下:默认情况下,Jackson将所有JSON处理为 java.util.Map 实例,同时Commons Beanutils简化了对象的属性访问,包括数组和映射支持。



所以你可以像这样使用它:

  //实际上它是一个Map实例,其映射字段位于
之内对象jsonObj = objectMapper.readValue(json,Object.class);

Object hello = PropertyUtils.getProperty(jsonObj,data.data2.value)

System.out.println(hello); //打印你好


I was wondering if somewhere out there exists a java librery able to query a JSONObject. In more depth I'm looking for something like:

String json = "{ data: { data2 : { value : 'hello'}}}";

...
// Somehow we managed to convert json to jsonObject
...

String result = jsonObject.getAsString("data.data2.value");

System.out.println(result);

I expect to get "hello" as output.

By now, the fastest way I have found is using Gson:

jsonObject.getAsJsonObject("data").getAsJsonObject().get("data2").getAsJsonObject("value").getAsString();

It's not actually easy to write and read. Is there something faster?

解决方案

First of all, I would recommend consider JSON object binding.

But in case if you get arbitrary JSON objects and you would like process them in the way you described, I would suggest combine Jackson JSON processor along with Apache's Commons Beanutils.

The idea is the following: Jackson by default process all JSON's as java.util.Map instances, meanwhile Commons Beanutils simplifies property access for objects, including arrays and Map supports.

So you may use it something like this:

//actually it is a Map instance with maps-fields within
Object jsonObj = objectMapper.readValue(json, Object.class);

Object hello = PropertyUtils.getProperty(jsonObj, "data.data2.value")

System.out.println(hello); //prints hello

这篇关于在java中查询JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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