为了账号安全,请及时绑定邮箱和手机立即绑定

使用Jackson将Java对象转换为JSON

使用Jackson将Java对象转换为JSON

陪伴而非守候 2019-08-30 16:32:49
我希望我的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输出?
查看完整描述

3 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

object要用杰克逊转换你的JSON:


ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();

String json = ow.writeValueAsString(object);


查看完整回答
反对 回复 2019-08-30
?
千万里不及你

TA贡献1784条经验 获得超9个赞

这可能很有用:


objectMapper.writeValue(new File("c:\\employee.json"), employee);


// display to console

Object json = objectMapper.readValue(

     objectMapper.writeValueAsString(employee), Object.class);


System.out.println(objectMapper.writerWithDefaultPrettyPrinter()

     .writeValueAsString(json));


查看完整回答
反对 回复 2019-08-30
  • 3 回答
  • 0 关注
  • 1332 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号