Russell Quinlan
Russell Quinlan

Reputation: 157

How to change name of fields when serialized exposed fields using Gson?

I am using Gson to serialize a Java object and return a json string. The object has many fields, but I'm trying to return 4 in particular. I'm using the @Expose annotation to tell Gson to ignore any other fields, but I would also like to be able to change the name of these fields to be returned. Using GsonBuilder this way

Gson gsonBuilder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();

I am able to only get only fields with @Expose. Is there a way to use @SerializedName along with @Expose, to change the name of these fields before they are returned? Using both annotations blocks anything from being returned, but I'm also finding that using just the @SerializedName annotation (and removing .excludeFieldsWithoutExposeAnnotation()) also prevents those fields from being returned.

Upvotes: 0

Views: 2689

Answers (1)

Tad Harrison
Tad Harrison

Reputation: 1293

You are on the right track. Here's a working example:

package test;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class MyData {
  @Expose
  private String id;

  @Expose
  @SerializedName("fileOriginalName")
  private String myFilename;

  @Expose
  @SerializedName("fileOriginalPath")
  private String myPath;

  private String myName;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getMyFilename() {
    return myFilename;
  }

  public void setMyFilename(String myFilename) {
    this.myFilename = myFilename;
  }

  public String getMyPath() {
    return myPath;
  }

  public void setMyPath(String myPath) {
    this.myPath = myPath;
  }

  public String getMyName() {
    return myName;
  }

  public void setMyName(String myName) {
    this.myName = myName;
  }

}

And the caller:

package test;

import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class Demo {
  static final Type MYDATA_TYPE = new TypeToken<MyData>() {
  }.getType();
  public static void main(String[] args){
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();

    MyData d = new MyData();

    d.setId("10");
    d.setMyFilename("was called myFilename");
    d.setMyName("should not be visible");
    d.setMyPath("was called myPath");

    String json = gson.toJson(d, MYDATA_TYPE);
    System.out.println(json);
  }
}

Here is the output:

{
  "id": "10",
  "fileOriginalName": "was called myFilename",
  "fileOriginalPath": "was called myPath"
}

Upvotes: 1

Related Questions