Fastjson BeanToArray
fastjson에서는 BeanToArray라는 매핑 모드가 지원됩니다. 일반 모드에서 JavaBean은 json 객체에 매핑되고 BeanToArray 모드는 json 배열에 매핑됩니다.
Sample 1
class Mode { public int id; public int name; } Model model = new Model(); model.id = 1001; model.name = "gaotie"; // {"id":1001,"name":"gaotie"} String text_normal = JSON.toJSONString(model); // [1001,"gaotie"] String text_beanToArray = JSON.toJSONString(model, SerializerFeature.BeanToArray); // support beanToArray & normal mode JSON.parseObject(text_beanToArray, Feature.SupportArrayToBean);
위의 예에서 BeanToArray 모드에서는 Key 출력이 적어 공간이 절약되고 json 문자열이 더 작아지며 성능이 더 좋아집니다.
Sample 2
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);
이 예에서 Company에 속성 부서 요소가 많은 경우 로컬에서 BeanToArray를 사용하면 좋은 성능을 얻을 수 있으며 전체 Get 더 나은 가독성.
샘플 3
이전 예제는 다음과 같이 작성할 수도 있습니다.
class Company { public int code; @JSONField(serialzeFeatures=SerializerFeature.BeanToArray, parseFeatures=Feature.SupportArrayToBean) public List<Department> departments = new ArrayList<Department>(); }
Performance
BeanToArray 모드를 사용하면 protobuf와 비슷한 성능을 얻을 수 있습니다.
create ser deser total size +dfl protobuf 244 2297 1296 3593 239 149 json/fastjson_array/databind 123 1289 1567 2856 281 163 msgpack/databind 122 1525 2180 3705 233 146 json/fastjson/databind 120 2019 2610 4629 486 262 json/jackson+afterburner/databind 118 2142 3147 5289 485 261 json/jackson/databind 124 2914 4411 7326 485 261
여기의 json/fastjson_array/databind는 BeanToArray 모드를 활성화하는 fastjson입니다. 전체 성능은 protobuf보다 좋습니다. fastjson Benchmark