如何在Java中查询JSON对象? [英] How to query a json object in java?

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

问题描述

我有一个test.json文件,其中包含数据:

I have a test.json file with data:

{
  "name":"tet",
  "id":"1",
  "age" : "34"
}

现在,当我查询select * from test;时,应该将结果显示为

Now when I query select * from test; should show me the result as

name id age
-----------
tet  1   34

是否可以像查询XML一样直接查询JSON对象?

Is it possible to directly query a JSON Object as we do for XML?

推荐答案

如果要创建一个满足您要求的新类,则无法直接从Json进行查询,或者可以使用ObjectMapper (从jackson-all-1.9.0.jar下载并添加到您的类路径中),并创建一个新的传输对象TestTO.java公开设置器和获取器,您将获得如下数据.

there is no way to query directly from the Json, if you want you have to create a new class that will do your requirement, OR you can use the ObjectMapper (download and add to your class path) from jackson-all-1.9.0.jar, and create a new transfer Object TestTO.java expose the setters and getters you will get your data like below..

1.创建TestTO.java

1.create TestTO.java

public class TestTO{

private String name;
private int id;
private int age;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}

}

2.从对象读取数据.

2.read your data from the object.

            final ObjectMapper mapper = new ObjectMapper();
            Test test = mapper.readValue(yourJson.json, TestTO.class);
            String name = test.getName();
            int id = test.getId();
            int age = test.getAge();

如果您的json包含多个测试对象,请使用如下所示的测试数组,它将为您提供测试数组,您可以遍历并获取数据,如下所示.

if your json contains the multiple test objects, use an test array like below, it will give you the array of tests, you can iterate over and get the data, like below.

            final ObjectMapper mapper = new ObjectMapper();
            TestTO[] test = mapper.readValue(yourJson.json, TestTO.class[]);
            for(Test tst:test){
            String name = test.getName();
            int id = test.getId();
            int age = test.getAge();
           }

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

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