使用Jackson将Java对象转换为JSON

283

我希望我的JSON数据看起来像这样:

{
    "information": [{
        "timestamp": "xxxx",
        "feature": "xxxx",
        "ean": 1234,
        "data": "xxxx"
    }, {
        "timestamp": "yyy",
        "feature": "yyy",
        "ean": 12345,
        "data": "yyy"
    }]
}

目前代码:

import java.util.List;

public class ValueData {

    private List<ValueItems> information;

    public ValueData(){

    }

    public List<ValueItems> getInformation() {
        return information;
    }

    public void setInformation(List<ValueItems> information) {
        this.information = information;
    }

    @Override
    public String toString() {
        return String.format("{information:%s}", information);
    }

}

public class ValueItems {

    private String timestamp;
    private String feature;
    private int ean;
    private String data;


    public ValueItems(){

    }

    public ValueItems(String timestamp, String feature, int ean, String data){
        this.timestamp = timestamp;
        this.feature = feature;
        this.ean = ean;
        this.data = data;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public String getFeature() {
        return feature;
    }

    public void setFeature(String feature) {
        this.feature = feature;
    }

    public int getEan() {
        return ean;
    }

    public void setEan(int ean) {
        this.ean = ean;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return String.format("{timestamp:%s,feature:%s,ean:%s,data:%s}", timestamp, feature, ean, data);
    }
}

我只是不知道如何使用Jackson将Java对象转换为JSON:

public static void main(String[] args) {
   // CONVERT THE JAVA OBJECT TO JSON HERE
    System.out.println(json);
}

我的问题是:我的类是否正确?我应该调用哪个实例,以及如何获得这个JSON输出?


4
以下教程可能会有所帮助:http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/ - maple_shaft
11个回答

0
使用Spring
    private static final ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule());
    ...
    json = objectMapper.writeValueAsString(SomeObject);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接