FastJson 下划线转驼峰

时间:2025-02-16 08:42:27

开发中存在一个需求,需要将下划线的json字符串,用驼峰的实体类接收。

@Data
@ToString
public class User{
	private String userName;
}
第一种

查了一些资料,提供了如下方法 进行转化:

String str = "{\"user_name\":123}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy.SNAKE_CASE);
System.out.println(objectMapper.readValue(str, User.class));
第二种

上面的方法确实可行,不过不太符合我们通常的使用习惯。 所以查看了一下构造方法,发现了下面这种符合通常使用习惯的写法

public static void main(String[] args) throws IOException {
     String str = "{\"user_name\":123}";
     ParserConfig parserConfig = new ParserConfig();
     parserConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
     User user = JSON.parseObject(str, User.class, parserConfig);
     System.out.println(user);
}

输出结果:

User(userName=123)

参考文章: fastjson 转下划线_fastjson 变量驼峰形式与下划线互转