google / google/gson

Extending JsonReader

Open
#1,453 2 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

I'm trying to extend `JsonReader`, but I'm blocked because I can't access field

```
/** The input JSON. */
private final Reader in;
```
member field that is passed in the constructor
```
public JsonReader(Reader in) {
if (in == null) {
throw new NullPointerException("in == null");
}
this.in = in;
}
```

Use case: I have written a PolymorphicTypeAdapterFactory that can serialize/deserialize inheritance class hierarchies. Btw, I hope you also would find this super cool :) It also supports generics! and supports 2 type name strategies: Type property `{"type":"square", "size": 5}` and object wrapper `{"square":{"size":5}}`.

For implementing the TypeAdapter for the type property strategy, I need to know the type name at the start of reading the object. But potentially, it is not the first property in the object. That's why I created a `TypePropertyJsonReader extends JsonReader`. It will return the `type` property as the first property of the object.

My TypePropertyJsonReader wraps the underlying JsonReader and buffers all the tokens until the `type` property is found. It then first passes all the buffered tokens (if any). And afterwards it delegates to the underlying JsonReader.

So I want a mechanism to pass the `in` Reader from the original JsonReader to the super class of my wrapper JsonReader. Like eg
* Make the field `private final Reader in;` protected
* A second constructor `protected JsonReader(JsonReader jsonReader)` where the `in` is taken from the passed jsonReader
* A getter `public Reader getIn()`

Do you want me to submit a Pull request for one of these options?

Are you interested in my polymorphic type adapter factory? And I would be excited to contribute that if you want it. These tests are easy to read and should give an idea of the capabilities: https://github.com/shape-ai/basics/tree/master/basics-gson/src/test/java/ai/shape/basics/gson

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.