javajsonserializationgson

Object Serialization to JSON (using Gson). How to set field names in UpperCamelCase?


I need to serialize a list of simple Java objects to JSON using Google Gson library.

The object:

public class SimpleNode {
    private String imageIndex;
    private String text;

    public String getImageIndex() {
        return imageIndex;
    }

    public void setImageIndex(String imageIndex) {
        this.imageIndex = imageIndex;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
       this.text = text;
    }
}

I have written the following code for serialization:

 List<SimpleNode> testNodes = repository.getElements(0);
 Gson gson = new Gson();
 String jsonNodesAsString = gson.toJson(testNodes);

It works, but the field name of the JSON objects is lowerCamelCase. Like this:

[
  {
    "imageIndex": "1",
    "text": "Text 1"
  },
  {
    "imageIndex": "2",
    "text": "Text 2"
  }
]

How do I get a JSON with UpperCamelCase field name, like this:

[
  {
    "ImageIndex": "1",
    "Text": "Text 1"
  },
  {
    "ImageIndex": "2",
    "Text": "Text 2"
  }
]

I think that I can rename member variables in to UpperCamelCase, but may be there is another way?


Solution

  • Taken from the docs:

    Gson supports some pre-defined field naming policies to convert the standard Java field names (i.e. camel cased names starting with lower case --- "sampleFieldNameInJava") to a JSON field name (i.e. sample_field_name_in_java or SampleFieldNameInJava). See the FieldNamingPolicy class for information on the pre-defined naming policies.

    It also has an annotation based strategy to allows clients to define custom names on a per-field basis using the @SerializedName annotation. Note that the annotation based strategy has field name validation which will raise "Runtime" exceptions if an invalid field name is provided as the annotation value.

    The following is an example of how to use both Gson naming policy features:

    private class SomeObject {
      @SerializedName("custom_naming") 
      private final String someField;
      
      private final String someOtherField;
    
      public SomeObject(String a, String b) {
        this.someField = a;
        this.someOtherField = b;
      }
    }
    
    SomeObject someObject = new SomeObject("first", "second");
    Gson gson = new GsonBuilder()
        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
        .create();
    
    String jsonRepresentation = gson.toJson(someObject);
    System.out.println(jsonRepresentation);
    

    Outputs:

    {"custom_naming":"first","SomeOtherField":"second"}
    

    However, for what you want, you could just use this:

    Gson gson = new GsonBuilder()
        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
        .create();
    

    By using the UPPER_CAMEL_CASE policy you'll achieve your goal.