Fastjson Bean转换为json Array简介说明

书欣 fastjson 发布时间:2022-07-24 23:22:43 阅读数:5507 1
下文笔者讲述Fastjson中将Bean直接转换为json Array的方法分享,如下所示
实现思路:
    只需在实体类上加入
	@JSONType(serialzeFeatures=SerializerFeature.BeanToArray, parseFeatures=Feature.SupportArrayToBean)
	注解即可实现Bean转换为Array的效果
例:
class Mode {
   public int id;
   public int name;
}

Model model = new Model();
model.id = 88888;
model.name = "java265";

// {"id":88888,"name":"java265"}
String txt = JSON.toJSONString(model); 

// [88888,"java265"]
String str = JSON.toJSONString(model, SerializerFeature.BeanToArray); 

// support 
JSON.parseObject(str, Feature.SupportArrayToBean); 
例:
class Company {
     public int code;
     public list<Department> departments = new ArrayList<Department>();
}

@JSONType(serialzeFeatures=SerializerFeature.BeanToArray, parseFeatures=Feature.SupportArrayToBean)
class Department {
     public int id;
     public Stirng name;
     public Department() {}
     public Department(int id, String name) {this.id = id; this.name = name;}
}


Company company = new Company();
company.code = 111;
company.departments.add(new Department(888, "dep1"));
company.departments.add(new Department(999, "dep2"));

// {"code"111,"departments":[[888,"dep1"],[999,"dep2"]]}
String text = JSON.toJSONString(commpany); 
class Company {
     public int code;

     @JSONField(serialzeFeatures=SerializerFeature.BeanToArray, parseFeatures=Feature.SupportArrayToBean)
     public List<Department> departments = new ArrayList<Department>();
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/fastjson/2022/4047.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者