简介
有多种命名策略:
- FieldNamingPolicy.IDENTITY
- FieldNamingPolicy.UPPER_CAMEL_CASE
- FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES
- FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES
- 等等
具体可以参看源码。
代码示例
示例:字段命名使用小写字母和下划线
package org.example;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.Data;
import org.junit.jupiter.api.Test;
public class TestGson {
@Data
public static class UserInfo {
private String useName;
}
@Test
public void test_01() {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
UserInfo userInfo = new UserInfo();
userInfo.setUseName("李白");
String jsonStr = gson.toJson(userInfo);
System.out.println(jsonStr);
// 以上代码输出: {"use_name":"李白"}
}
@Test
public void test_02() {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
UserInfo userInfo = gson.fromJson("{\"use_name\":\"李白\"}", UserInfo.class);
System.out.println(userInfo);
// 以上代码输出: TestGson.UserInfo(useName=李白)
}
}