GSON JSON parsing based on Generic return?

public static<K> K fromJSON(String jsonData) {
return OpenRedisJSON.gson.fromJson(jsonData, K.class); // want something like this.
}
public static<K> K fromJSON(String jsonData) {
return OpenRedisJSON.gson.fromJson(jsonData, K.class); // want something like this.
}
11 Replies
JavaBot
JavaBot2y ago
This post has been reserved for your question.
Hey @daysling! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
szatkus
szatkus2y ago
Not possible. You need to pass a class by an argument. Java has no way to infer that.
Kyo-chan
Kyo-chan2y ago
Reminder that generics don't exist at runtime. Declared types that do things like class StringList extends List<String> can be analyzed at runtime to detect they're a List of Strings. But nothing else stays.
0x150
0x1502y ago
EXCEPT with some smart compiler magic, you can actually get the "generic" type of a method
Kyo-chan
Kyo-chan2y ago
Not sure what you mean
0x150
0x1502y ago
<T> void test(T... dontFillMe) {
Class<T> tClass = (Class<T>) dontFillMe.getClass().getComponentType();
}
<T> void test(T... dontFillMe) {
Class<T> tClass = (Class<T>) dontFillMe.getClass().getComponentType();
}
it's very hacky but it does work
0x150
0x1502y ago
No description
Kyo-chan
Kyo-chan2y ago
I see. Hadn't seen this hack before
0x150
0x1502y ago
it is extraordinarily hacky but it's something i wish with all my heart that generics will become actually good at some point
Kyo-chan
Kyo-chan2y ago
It is another thing that stays, as indeed the compiler magic creates an array of the expected return type. But it is not something I'd tell someone they may do
JavaBot
JavaBot2y ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?