當你有一個字段是字符串類型,裏面是json格式數據,你但願直接輸入,而不是通過轉義以後再輸出,這時使用 jsonDirect=true
參數,如:git
import com.alibaba.fastjson.annotation.JSONField; public static class Model { public int id; @JSONField(jsonDirect=true) public String value; }
若想將嵌套對象的字段 放到當前層級,可以使用 unwraped=true
參數, 如:github
public static class VO { public int id; @JSONField(unwrapped = true) public Localtion localtion; } public static class Localtion { public int longitude; public int latitude; public Localtion() {} public Localtion(int longitude, int latitude) { this.longitude = longitude; this.latitude = latitude; } } VO vo = new VO(); vo.id = 123; vo.localtion = new Localtion(127, 37); String text = JSON.toJSONString(vo); Assert.assertEquals("{\"id\":123,\"latitude\":37,\"longitude\":127}", text); VO vo2 = JSON.parseObject(text, VO.class); assertNotNull(vo2.localtion); assertEquals(vo.localtion.latitude, vo2.localtion.latitude); assertEquals(vo.localtion.longitude, vo2.localtion.longitude);
當返回的 json 數據包含列表,想省去字段名節省空間時,可以使用 BeanToArray
特性,如:json
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 = 100; company.departments.add(new Department(1001, "Sales")); company.departments.add(new Department(1002, "Financial")); // {"code":10,"departments":[[1001,"Sales"],[1002,"Financial"]]} String text = JSON.toJSONString(commpany);