jackson json java对象,使用Jackson将Java对象转换为JSON
发布日期:2022-02-19 00:02:17 浏览次数:9 分类:技术文章

本文共 1874 字,大约阅读时间需要 6 分钟。

I want my JSON to look like this:

{

"information": [{

"timestamp": "xxxx",

"feature": "xxxx",

"ean": 1234,

"data": "xxxx"

}, {

"timestamp": "yyy",

"feature": "yyy",

"ean": 12345,

"data": "yyy"

}]

}

Code so far:

import java.util.List;

public class ValueData {

private List information;

public ValueData(){

}

public List getInformation() {

return information;

}

public void setInformation(List information) {

this.information = information;

}

@Override

public String toString() {

return String.format("{information:%s}", information);

}

}

and

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);

}

}

I just missing the part how I can convert the Java object to JSON with Jackson:

public static void main(String[] args) {

// CONVERT THE JAVA OBJECT TO JSON HERE

System.out.println(json);

}

My Question is: Are my classes correct? Which instance do I have to call and how that I can achieve this JSON output?

解决方案

To convert your object in JSON with Jackson:

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

String json = ow.writeValueAsString(object);

转载地址:https://blog.csdn.net/weixin_34236334/article/details/118823691 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:mysql 查session,使用PHP SESSION变量存储MySQL查询结果
下一篇:html 中objectn 上传flash 设置透明属性,【flash8 ActionScript】对象

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月01日 23时48分29秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章