How to prevent Gson serialize / deserialize the first character of a field (underscore)?

gson, json, parsing

Solution

`GsonBuilder` provides a method `setFieldNamingStrategy()` that allows you to pass your own `FieldNamingStrategy` implementation.

Note that this replaces the call to `setFieldNamingPolicy()` - if you look at the source for `GsonBuilder` these two methods are mutually exclusive as they set the same internal field (The `FieldNamingPolicy` enum is a `FieldNamingStrategy`).

public class App
{
    public static void main(String[] args)
    {
        Gson gson = new GsonBuilder()
                        .setFieldNamingStrategy(new MyFieldNamingStrategy())
                        .setPrettyPrinting()
                        .create();

        System.out.println(gson.toJson(new ExampleBean()));
    }
}

class ExampleBean
{

    private String _firstField = "first field value";
    private String _secondField = "second field value";
    // respective getters and setters
}

class MyFieldNamingStrategy implements FieldNamingStrategy
{
    public String translateName(Field field)
    {
        String fieldName = 
            FieldNamingPolicy.UPPER_CAMEL_CASE.translateName(field);
        if (fieldName.startsWith("_"))
        {
            fieldName = fieldName.substring(1);
        }
        return fieldName;
    }
}

Output:

{
  "FirstField": "first field value",
  "SecondField": "second field value"
}

Problem

My class: ``` class ExampleBean { private String _firstField; private String _secondField; // respective getters and setters } ``` I want to appear as follows: ``` { "FirstField":"value", "SecondField":"value" } ``` And not like this ``` { "_FirstField":"value", "_SecondField":"value" } ``` I initialize the parser as follows: ``` GsonBuilder builder = new GsonBuilder(); builder.setDateFormat(DateFormat.LONG); builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE); builder.setPrettyPrinting(); set_defaultParser(builder.create()); ``` I could see the API and in the documentation of "FieldNamePolicy" but I am surprised that not give the option to skip "_" I also know I can use the annotation... ``` @ SerializedName (" custom_naming ") ``` ...but do not want to have to write this for alllllll my fields ... It's very useful for me to distinguish between local variables and fields of a class. :( Any Idea? EDIT: There would be many obvious solutions, (inheritance, gson overwriting methods, regular expresions). My question is more focused on whether there is a native solution of gson or a less intrusive fix? Maybe we could propose as new FieldNamePolicy?

Original source