-
Notifications
You must be signed in to change notification settings - Fork 4.3k
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
@JsonAdapter + JsonDeserializer make JsonSerializer fail #1783
Comments
It looks like this describes the same problem as #1326 (though that issue is not as detailed). The underlying issue is similar to #1028: Because For now a workaround could be to use a @Data
public static class DataValue {
@JsonAdapter(StringListTypeAdapterFactory.class)
private List<String> list;
}
/**
* Custom TypeAdapterFactory for {@code List<String>}.
*
* <p>Only intended for usage with {@link JsonAdapter @JsonAdapter} on fields.
*/
private static class StringListTypeAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
// Cannot use getDelegateAdapter(...) due to https://github.com/google/gson/issues/1028
// However if this factory is only used with @JsonAdapter on
// fields then using getAdapter(...) is safe
@SuppressWarnings("unchecked")
TypeAdapter<List<String>> delegate = (TypeAdapter<List<String>>) gson.getAdapter(type);
TypeAdapter<List<String>> adapter = new TypeAdapter<List<String>>() {
@Override
public List<String> read(JsonReader in) throws IOException {
JsonToken peeked = in.peek();
if (peeked == JsonToken.NULL) {
return null;
} else if (peeked == JsonToken.BEGIN_ARRAY) {
return delegate.read(in);
} else if (peeked == JsonToken.STRING) {
String str = in.nextString();
return Arrays.asList(str.split(","));
} else {
return null;
}
}
@Override
public void write(JsonWriter out, List<String> value) throws IOException {
delegate.write(out, value);
}
};
@SuppressWarnings("unchecked")
TypeAdapter<T> result = (TypeAdapter<T>) adapter;
return result;
}
} |
…ing correct delegate
It appears this has been fixed by #2435; the output is now: {"list":["a","b","c","d","e","f"]} (though I omitted the Lombok I am therefore going to close this issue. But please let us know if you can still reproduce this with the latest Gson code from the |
I want to deserialize the string to list so I use
@JsonAdapter + JsonDeserializer
to solve the problem, but when I try to serialize the List, I get a{}
.The text was updated successfully, but these errors were encountered: