在不使用JsonNode的情况下读取JSON值

时间:2019-01-25 13:43:41

标签: java fasterxml

示例JSON格式如下:

// for DSN documentation, check http://php.net/manual/en/ref.pdo-mysql.connection.php
$handler = new MySqlSessionHandler ('mysql:host=mydb.foo.com;dbname=sessions;charset=utf8mb4','MySqlUsername','MySqlPassword');
session_set_save_handler($handler, true);
session_start();

使用上述JSON,我们使用以下代码获取{ myarray: [ { id: 123, title: "my title", name: "my name" }, { id: 456, title: "my title 2", name: "my name 2" } ] }

myarray

几天后,我们升级了json库,并抛出了以下例外。

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(con.getInputStream(), JsonNode.class);
def stations = mapper.readValue(node.get("myarray"), MyClass[].class);

是否有任何方法或解决方法可以在不使用JsonNode的情况下获取myarray对象?

(我们正在使用com.fasterxml.jackson.databind最新版本)

1 个答案:

答案 0 :(得分:0)

使用Jackson Databind版本2.9.8。

compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.8'

您需要找到myarray,然后检查它是否为数组。之后,您可以继续遍历其子级。其中data.json是包含JSON数据的文件。

StationParser.java

import java.io.IOException;
import java.io.InputStream;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

public class StationParser {
    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        InputStream ios = Library.class.getClassLoader().getResourceAsStream("data.json");
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode data = (ArrayNode) mapper.readTree(ios).get("myarray");
        Station[] stations = mapper.readValue(data.traverse(), Station[].class);

        for (Station station : stations) {
            System.out.println(station);
        }
    }
}

输出

Station [id=123, title=my title, name=my name]
Station [id=456, title=my title 2, name=my name 2]

Station.java

public class Station {
    private long id;
    private String title;
    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return String.format("Station [id=%s, title=%s, name=%s]", id, title, name);
    }
}