Skip to content

Throw exception when using classes from other JSON libraries with Gson #2445

@Marcono1234

Description

@Marcono1234

Problem solved by the feature

Quite frequently users seem to accidentally use JSON classes from other libraries with Gson, such as JSON-java's JSONObject. This leads to incorrect results because Gson will then fall back to using reflection on these classes.

Examples:

Related:

Relates to #673, #782

Feature description

Register a default TypeAdapter (or TypeAdapterFactory) which checks if the class is from a different popular JSON library and in that case throw an exception.

  • The exception should only be thrown in the read and write methods of TypeAdapter to minimize the risk of backward incompatibility when users don't actually serialize or deserialize the instances
  • The adapter should act as fallback (internally registered right before the reflection-based factory); a user defined adapter should have higher precedence
  • The exception message mention that the class is unsupported and the Gson equivalent should be used; optionally it should also point to a new troubleshooting guide entry

Libraries with JSON classes which should be detected:

  • JSON-java (these are also the ones available for Android)
  • Jackson
    Might not be necessary because the Jackson classes have different naming (ObjectNode for JSON object, ArrayNode for JSON array, though the base class is named JsonNode), so the risk of confusion might be lower
  • Vert.x ?
  • json-simple
    Probably not necessary because JSONArray extends ArrayList and JSONObject extends HashMap
  • fastjson
    Probably not necessary because JSONArray implements List and JSONObject implements Map
  • json-smart
    Probably not necessary because JSONArray extends ArrayList and JSONObject extends HashMap
  • ...?

Note that this would break backward compatibility for applications which (accidentally) rely on this, but they could register a custom TypeAdapter to restore the functionality.

Alternatives / workarounds

  • Do nothing
  • Add default adapters which support third-party JSON classes; probably not something we want to do?

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