MissBonbon
MissBonbon

Reputation: 161

GSON - Optional and required fields with naming policy

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.

Upvotes: 1

Views: 5353

Answers (1)

Pavan Kumar
Pavan Kumar

Reputation: 4820

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"}

Upvotes: 1

Related Questions