Bootstrap

Java Json 数据下划线与驼峰格式进行相互转换

概述

今天遇见一个需求,需要对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);
;