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

前端 未结 1 555
猫巷女王i
猫巷女王i 2020-12-05 04:36

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

The object:

public class SimpleNode {
    private String imageIn         


        
相关标签:
1条回答
  • 2020-12-05 05:01

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

    ======== OUTPUT ========

    {"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 option, you'll achieve your goal.

    0 讨论(0)
提交回复
热议问题