GSON - Optional and required fields with naming policy

喜欢而已 提交于 2019-12-24 09:49:50

问题


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();

Every key-value from JSON, that is in this case the deserialized java object need to be lowercase. Otherwise it will throw JsonParseException.

For example I have this class:

class TestClass {
  @JsonRequired
  private String testName;
  //getter & setter

Then this JSON-file can not be deserialized:

{
   "TestName":"name"
}

But I want to get sure that UPPER_CAMEL_CASE is used in this case. Thx.


回答1:


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));
}

Output

name
{"testName":"name"}


来源:https://stackoverflow.com/questions/42021699/gson-optional-and-required-fields-with-naming-policy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!