GSON-带有命名策略的可选和必填字段 [英] GSON - Optional and required fields with naming policy
问题描述
我需要一个函数,该函数读取json文件并控制json文件的结构.应该定义必填字段.为了那个原因 我找到了一个问题,可以解决部分问题 Gson可选和必填字段.但是在这种情况下,命名约定不再有效.就我而言,我使用了以下GsonBuilder:
I need a function, that reads a json file and control the structur of the json file. Required fields should be defined. For that I found a question that resolve a part of my problem Gson optional and required fields. But in this case the naming convention has not power any more. In my case I used following GsonBuilder:
this.gsonUpperCamelCase = new GsonBuilder()
.registerTypeAdapter(TestClass.class, new AnnotatedDeserializer<TestClass>())
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
JSON中的每个键值,在这种情况下,反序列化的Java对象必须为小写.否则它将抛出JsonParseException.
Every key-value from JSON, that is in this case the deserialized java object need to be lowercase. Otherwise it will throw JsonParseException.
例如,我有这个课程:
class TestClass {
@JsonRequired
private String testName;
//getter & setter
然后无法反序列化此JSON文件:
Then this JSON-file can not be deserialized:
{
"TestName":"name"
}
但是我想确保在这种情况下使用UPPER_CAMEL_CASE.谢谢.
But I want to get sure that UPPER_CAMEL_CASE is used in this case. Thx.
推荐答案
SerializedName
是可以帮助您解决此问题的注释.如下修改TestClass
,您应该能够使用TestName
,tn
,tn2
反序列化JSON,并且在序列化时始终使用testName
.
SerializedName
is the annotation that can help you on this. Modifying the TestClass
as below, you should be able to deserialize a JSON with TestName
, tn
, tn2
and when serializing, it always uses testName
.
static class TestClass {
@JsonRequired
@SerializedName(value="testName", alternate = {"TestName", "tn", "tn2"})
private String testName;
}
public static void main(String[] args) {
Gson gsonUpperCamelCase = new GsonBuilder()
.registerTypeAdapter(TestClass.class,
new AnnotatedDeserializer<TestClass>())
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
TestClass tc = gsonUpperCamelCase.fromJson("{\r\n" +
" \"TestName\":\"name\"\r\n" +
"}", TestClass.class);
System.out.println(tc.testName);
System.out.println(gsonUpperCamelCase.toJson(tc));
}
输出
name
{"testName":"name"}
这篇关于GSON-带有命名策略的可选和必填字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!