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 8184597
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T01:33:36+00:00 2026-06-07T01:33:36+00:00

I’ve seen plenty of simple examples of using a custom TypeAdapter. The most helpful

  • 0

I’ve seen plenty of simple examples of using a custom TypeAdapter. The most helpful has been Class TypeAdapter<T>. But that hasn’t answered my question yet.

I want to customize the serialization of a single field in the object and let the default Gson mechanism take care of the rest.

For discussion purposes, we can use this class definition as the class of the object I wish to serialize. I want to let Gson serialize the first two class members as well as all exposed members of the base class, and I want to do custom serialization for the 3rd and final class member shown below.

public class MyClass extends SomeClass {

@Expose private HashMap<String, MyObject1> lists;
@Expose private HashMap<String, MyObject2> sources;
private LinkedHashMap<String, SomeClass> customSerializeThis;
    [snip]
}
  • 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-07T01:33:38+00:00Added an answer on June 7, 2026 at 1:33 am

    This is a great question because it isolates something that should be easy but actually requires a lot of code.

    To start off, write an abstract TypeAdapterFactory that gives you hooks to modify the outgoing data. This example uses a new API in Gson 2.2 called getDelegateAdapter() that allows you to look up the adapter that Gson would use by default. The delegate adapters are extremely handy if you just want to tweak the standard behavior. And unlike full custom type adapters, they’ll stay up-to-date automatically as you add and remove fields.

    public abstract class CustomizedTypeAdapterFactory<C>
        implements TypeAdapterFactory {
      private final Class<C> customizedClass;
    
      public CustomizedTypeAdapterFactory(Class<C> customizedClass) {
        this.customizedClass = customizedClass;
      }
    
      @SuppressWarnings("unchecked") // we use a runtime check to guarantee that 'C' and 'T' are equal
      public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        return type.getRawType() == customizedClass
            ? (TypeAdapter<T>) customizeMyClassAdapter(gson, (TypeToken<C>) type)
            : null;
      }
    
      private TypeAdapter<C> customizeMyClassAdapter(Gson gson, TypeToken<C> type) {
        final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);
        final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
        return new TypeAdapter<C>() {
          @Override public void write(JsonWriter out, C value) throws IOException {
            JsonElement tree = delegate.toJsonTree(value);
            beforeWrite(value, tree);
            elementAdapter.write(out, tree);
          }
          @Override public C read(JsonReader in) throws IOException {
            JsonElement tree = elementAdapter.read(in);
            afterRead(tree);
            return delegate.fromJsonTree(tree);
          }
        };
      }
    
      /**
       * Override this to muck with {@code toSerialize} before it is written to
       * the outgoing JSON stream.
       */
      protected void beforeWrite(C source, JsonElement toSerialize) {
      }
    
      /**
       * Override this to muck with {@code deserialized} before it parsed into
       * the application type.
       */
      protected void afterRead(JsonElement deserialized) {
      }
    }
    

    The above class uses the default serialization to get a JSON tree (represented by JsonElement), and then calls the hook method beforeWrite() to allow the subclass to customize that tree. Similarly for deserialization with afterRead().

    Next we subclass this for the specific MyClass example. To illustrate I’ll add a synthetic property called ‘size’ to the map when it’s serialized. And for symmetry I’ll remove it when it’s deserialized. In practice this could be any customization.

    private class MyClassTypeAdapterFactory extends CustomizedTypeAdapterFactory<MyClass> {
      private MyClassTypeAdapterFactory() {
        super(MyClass.class);
      }
    
      @Override protected void beforeWrite(MyClass source, JsonElement toSerialize) {
        JsonObject custom = toSerialize.getAsJsonObject().get("custom").getAsJsonObject();
        custom.add("size", new JsonPrimitive(custom.entrySet().size()));
      }
    
      @Override protected void afterRead(JsonElement deserialized) {
        JsonObject custom = deserialized.getAsJsonObject().get("custom").getAsJsonObject();
        custom.remove("size");
      }
    }
    

    Finally put it all together by creating a customized Gson instance that uses the new type adapter:

    Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(new MyClassTypeAdapterFactory())
        .create();
    

    Gson’s new TypeAdapter and TypeAdapterFactory types are extremely powerful, but they’re also abstract and take practice to use effectively. Hopefully you find this example useful!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I want to count how many characters a certain string has in PHP, but
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
Seemingly simple, but I cannot find anything relevant on the web. What is the
I'm making a simple page using Google Maps API 3. My first. One marker
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and

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.