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

代码实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 模型对象
*/
public class User {

//ID
public int userId;

//名称
public String userName;

//邮箱
public String userEmail;

//手机号
public String userPhone;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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);
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :