Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8195861
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T05:17:06+00:00 2026-06-07T05:17:06+00:00

By default Gson uses fields as a basis for it’s serialization. Is there a

  • 0

By default Gson uses fields as a basis for it’s serialization. Is there a way to get it to use accessors instead?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T05:17:07+00:00Added an answer on June 7, 2026 at 5:17 am

    The developers of Gson say that they never felt swayed by the requests to add this feature and they were worried about murkying up the api to add support for this.

    One way of adding this functionality is by using a TypeAdapter (I apologize for the gnarly code but this demonstrates the principle):

    import java.io.IOException;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    import com.google.common.base.CaseFormat;
    import com.google.gson.Gson;
    import com.google.gson.TypeAdapter;
    import com.google.gson.reflect.TypeToken;
    import com.google.gson.stream.JsonReader;
    import com.google.gson.stream.JsonWriter;
    
    public class AccessorBasedTypeAdaptor<T> extends TypeAdapter<T> {
    
      private Gson gson;
    
      public AccessorBasedTypeAdaptor(Gson gson) {
        this.gson = gson;
      }
    
      @SuppressWarnings("unchecked")
      @Override
      public void write(JsonWriter out, T value) throws IOException {
        out.beginObject();
        for (Method method : value.getClass().getMethods()) {
          boolean nonBooleanAccessor = method.getName().startsWith("get");
          boolean booleanAccessor = method.getName().startsWith("is");
          if ((nonBooleanAccessor || booleanAccessor) && !method.getName().equals("getClass") && method.getParameterTypes().length == 0) {
            try {
              String name = method.getName().substring(nonBooleanAccessor ? 3 : 2);
              name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, name);
              Object returnValue = method.invoke(value);
              if(returnValue != null) {
                TypeToken<?> token = TypeToken.get(returnValue.getClass());
                TypeAdapter adapter = gson.getAdapter(token);
                out.name(name);
                adapter.write(out, returnValue);
              }
            } catch (Exception e) {
              throw new ConfigurationException("problem writing json: ", e);
            }
          }
        }
        out.endObject();
      }
    
      @Override
      public T read(JsonReader in) throws IOException {
        throw new UnsupportedOperationException("Only supports writes.");
      }
    }
    

    You can register this as a normal type adapter for a given type or through a TypeAdapterfactory – possibly checking for the presence of a runtime annotation:

    public class TypeFactory implements TypeAdapterFactory {
    
      @SuppressWarnings("unchecked")
      public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
        Class<? super T> t = type.getRawType();
        if(t.isAnnotationPresent(UseAccessor.class)) {
         return (TypeAdapter<T>) new AccessorBasedTypeAdaptor(gson);
        }
        return null;
      }
    

    This can be specified as normal when creating your gson instance:

    new GsonBuilder().registerTypeAdapterFactory(new TypeFactory()).create();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

By default, the activemq uses tcp protocol. But now, I change it to use
Default JVM uses maximum 1.5 GB RAM/JVM Java application. But my Server have 8
By default, the ordered list looks like this: There are some spacing on the
The default strongly-typed Edit page in ASP.NET MVC 3 generally exposes all fields for
By default, there are 5 bands that android provide in its Equalizer class. I
By default, Visual Studio compiles a project to use the Multi Threaded DLL, found
Default, Windows controls don't have DoubleBuffer. When I use it, I can reduce flicker.
The default user registration page in Drupal 7 has fields to enter a username,
By default Commerce Server's pipelines log to %WEBROOT%\pipelines\log , is there a configuration value
By default, iOS’s keyboard sets the first letter in text form fields (including type=email

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.