Fastjson Bean转换为json Array简介说明
下文笔者讲述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>(); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。