Option to sort JSON output alphabetically
- Dominant language
- Java
- Stars
- 24.2k
- Forks
- 4.5k
- Avg merge
- 6d 4h
- Merged PRs (30d)
- 12
Description
# 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.
Contributor guide
Assessment
This issue has not been assessed yet.