fastjson 使用技巧

fastjson 使用技巧

当你有一个字段是字符串类型,里面是json格式数据,你希望直接输入,而不是经过转义之后再输出,这时使用 jsonDirect=true 参数,如:

import com.alibaba.fastjson.annotation.JSONField;

public static class Model {
    public int id;
    @JSONField(jsonDirect=true)
    public String value;
}

若想将嵌套对象的字段 放到当前层级,可使用 unwraped=true 参数, 如:

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 特性,如:

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

参考资料

  1. JSONField_unwrapped
  2. JSONField_jsonDirect_cn
  3. BeanToArray_cn
原文地址:https://www.cnblogs.com/xunux/p/7286736.html