FastJSON自定义序列化

FastJSON自定义序列化

对接第三方机构调用接口的时候 , 经常遇到返回来的JSON格式非常复杂的情况

例如返回的报文为以下形式 , 如果解析不好的话, 不利于存取和阅读

{
  "key":"x",
  "value":"y"
}

我们期望的报文格式应该为:

{
  "x":"y"
}

本文使用fastjson的ObjectDeserializer接口实现自定义JSON序列化

假设原始报文如下:

{
  "code": 0,
  "msg": "sucess",
  "data": {
    "personInfo": [
      {
        "key": "name",
        "value": "JOECD"
      },
      {
        "key": "age",
        "value": 50
      }
    ]
  }
}

目标报文如下:

{
  "code": 0,
  "msg": "sucess",
  "data": {
    "personInfo": {
      "age": 50,
      "name": "JOECD"
    }
  }
}

1.定义实体类

@Getter
@Setter
public class Person {

    private String name;

    private int age;

}
@Setter
@Getter
public class Result {

    private int code;

    private String msg;

    private ResultData data;

    @Setter
    @Getter
    private static class ResultData {
        private Person personInfo;
    }
}

2.创建自定义解析器

我们要序列化的JSON层级结构是personInfo这一层

public class PersonDeserializer implements ObjectDeserializer {

    @Override
    public Person deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        Person result = new Person();
        Class targetClass = Person.class;
        //拿到键值对
        List<Pair> infoList = parser.parseArray(Pair.class);
        for (Pair pair : infoList) {
        	//反射赋值
            Field field;
            try {
                field = targetClass.getDeclaredField(pair.getKey());
                field.setAccessible(true);
                field.set(result, pair.getValue());
            } catch (NoSuchFieldException | IllegalAccessException ignored) {

            }
        }
        return result;
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }

    @Setter
    @Getter
    private static class Pair {
        private String key;
        private Object value;
    }
}

3.给定义的字段加上解析器注解

@Setter
@Getter
private static class ResultData {
	@JSONField(deserializeUsing = PersonDeserializer.class)
    private Person personInfo;
}

4.运行,查看结果

public static void main(String[] args) {
        String jsonStr = "{\n" +
                "  \"code\": 0,\n" +
                "  \"msg\": \"sucess\",\n" +
                "  \"data\": {\n" +
                "    \"personInfo\": [\n" +
                "      {\n" +
                "        \"key\": \"name\",\n" +
                "        \"value\": \"JOECD\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"key\": \"age\",\n" +
                "        \"value\": 50\n" +
                "      }\n" +
                "    ]\n" +
                "  }\n" +
                "}";
        Result result = JSON.parseObject(jsonStr, Result.class);
        System.out.println(JSON.toJSONString(result));
}

输出:

{"code":0,"data":{"personInfo":{"age":50,"name":"JOECD"}},"msg":"sucess"}

5.最后

解析k-v型的JSON只是工作中刚好遇到一个例子,自定义JSON序列化还可以扁平化JSON,优化层级结构等等,大家可以自行开发

你可能感兴趣的:(工作实践)