实现对象字段在转换为 JSON 时大小写保持不变
预期效果:对象中字段名是 Age,NAME
转成json后:{"Age":"12","NAME":"张三"}
使用场景:给外系统传参数rest接口参数时,对方要求;
方式一 使用 Jackson 的@JsonProperty注解
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
class Person {
private String name;
@JsonProperty("Age") // 加了这个注解的可以保持大小写不变
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class JsonCasePreservationExample {
public static void main(String[] args) throws Exception {
Person person = new Person("Alice", 30);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(person);
System.out.println(json);
}
}
方式二 使用gson
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
class Person {
private String name;
private int Age;
public Person(String name, int age) {
this.name = name;
Age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
}
public class GsonCasePreservationExample {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(com.google.gson.FieldNamingPolicy.IDENTITY)
.create();
String json = gson.toJson(person);
System.out.println(json);
}
}
标签:String,int,age,字段,Person,JSON,大小写,public,name
From: https://www.cnblogs.com/xiaop27/p/18471412