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

▼魔方 西西 提交于 2019-12-17 17:54:35

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/22096274/object-serialization-to-json-using-gson-how-to-set-field-names-in-uppercamelc

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