Java Json 資料下劃線與駝峰格式進行相互轉換

NO IMAGE

概述

今天遇見一個需求,需要對json資料進行下劃線與駝峰格式之間進行轉換,在Fastjson、Jackson、Gson都提供了轉換的方式,在這裡進行一下列舉。

User類:

public class User {
private String nameInfo;
private String ageInfo;
public String getNameInfo() {
return nameInfo;
}
public void setNameInfo(String nameInfo) {
this.nameInfo = nameInfo;
}
public String getAgeInfo() {
return ageInfo;
}
public void setAgeInfo(String ageInfo) {
this.ageInfo = ageInfo;
}
}

Fastjson

// 生產環境中,config要做singleton處理,要不然會存在效能問題
User user = new User();
user.setNameInfo("coder");
user.setAgeInfo("28");
SerializeConfig config = new SerializeConfig();
config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
String json = JSON.toJSONString(user, config);
Assert.assertEquals("{\"age_info\":\"28\",\"name_info\":\"coder\"}", json);

Gson

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = gsonBuilder.create();
User user = new User();
user.setName("coder");
user.setAge(28);
String json = gson.toJson(user);
Assert.assertEquals("{\"age_info\":\"28\",\"name_info\":\"coder\"}", json);

Jackson

User user = new User();
user.setNameInfo("coder");
user.setAgeInfo("28");
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy.SNAKE_CASE);
String json = mapper.writeValueAsString(user);
Assert.assertEquals("{\"name_info\":\"coder\",\"age_info\":\"28\"}", json);