fastjson支持配置的PropertyNamingStrategy四种策略

PropertyNamingStrategy策略

FastJson默认使用CamelCase,在1.2.15版本之后,FastJson支持配置PropertyNamingStrategy,支持四种策略:CamelCasePascalCaseSnakeCaseKebabCase

属性名策略说明:

策略 对象属性 序列化后属性
CamelCase userId userId
PascalCase userId UserId
SnakeCase userId user_id
KebabCase userId user-id

代码实例

/**
 * 模型对象
 */
public class User {

    //ID
    public int userId;

    //名称
    public String userName;

    //邮箱
    public String userEmail;

    //手机号
    public String userPhone;
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;

public class FastJsonTest {

    public static void main(String[] args) {
        // 创建对象并赋值
        User user = new User();
        user.userId = 22;
        user.userName = "Joe.Ye";
        user.userEmail = "test@appblog.cn";
        user.userPhone = "10086";

        // 序列化配置对象
        SerializeConfig serializeConfig = new SerializeConfig(); 
        serializeConfig.propertyNamingStrategy = PropertyNamingStrategy.CamelCase;;

        // 序列化对象
        String json = JSON.toJSONString(user, serializeConfig);
        System.out.println("序列化 user json -> ");
        System.out.println(json);

        // 反序列化配置对象
        ParserConfig parserConfig = new ParserConfig(); 
        parserConfig.propertyNamingStrategy = PropertyNamingStrategy.CamelCase;

        // 反序列化对象
        user = JSON.parseObject(json, user.class, parserConfig);
        System.out.println("反序列化 user object -> ");
        System.out.print(user.userId + " ");
        System.out.print(user.userName + " ");
        System.out.print(user.userEmail + " ");
        System.out.println(user.userPhone);
    }
}
上一篇 fastjson可正常反序列化字符串null
下一篇 fastjson指定字段不序列化
目录
文章列表
1 Android WebView基本设置及监听设置
Android WebView基本设置及监听设置
2
Flutter Widget之Text
Flutter Widget之Text
3
SSH修改端口防暴力破解
SSH修改端口防暴力破解
4
设计模式(11)命令模式
设计模式(11)命令模式
5
以太坊学习3:以太坊客户端编译安装(geth和ethereumj)
以太坊学习3:以太坊客户端编译安装(geth和ethereumj)
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。