Skip to content

Option to sort JSON output alphabetically #2848

@patkovskyi

Description

@patkovskyi

Problem solved by the feature

Caching. A common pattern is to generate a request body using Gson. Another common pattern is to cache the response by using a hash of the request body as a cache key. Gson does not guarantee stable JSON order for some objects (notably, ImmutableSet/ImmutableMap), leading to non-deterministic cache keys for essentially the same requests.

Testing. If you want to test the serialization of object trees that contain ImmutableSet/ImmutableMap, you can't write string assertions now because Gson output is non-deterministic.

Feature description

new GsonBuilder().sortOutputAlphabetically().create() — serialize all JSON keys alphabetically. Deserializer works as before.

Maybe a better option would be something like: new GsonBuilder().setOutputOrdering(ALPHABETICAL).create()

Alternatives / workarounds

  1. Avoid using ImmutableSet/ImmutableMap. Unfortunately, you often have to serialize other teams' objects (sometimes coming from other libraries), making this recommendation impractical.
  2. Write your TypeAdapters. Hard, error-prone, and time-consuming. I'm still struggling to make it work. Would appreciate an example that enforces Set and Map ordering.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions