Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Marcono1234 opened this issue Jul 24, 2023 · 0 comments · May be fixed by #2452
Open

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

Marcono1234 opened this issue Jul 24, 2023 · 0 comments · May be fixed by #2452

Comments

@Marcono1234
Copy link
Collaborator

Marcono1234 commented Jul 24, 2023

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?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant