V
V
Vladislav Vinokurov2018-02-21 19:45:04
Java
Vladislav Vinokurov, 2018-02-21 19:45:04

Parsing Json-a into different objects?

On the client, you need to convert one of the three objects to json, say A, B, C.
The server accepts a json string and you need to parse it into an object, but using GSON you need to specifically specify the class
A a = json.fromJson(parse, A.class);
. What are the options if it is not known what type will come to the server? There is, of course, an option, to make the field String type = "the type of class we need" in each class and with the help of the factory and this type already drive into the desired type, but this does not look like a good option at all. How else can this be done? Thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2018-02-21
@zagayevskiy

In the general case, no way. If the fields of the classes are the same, there is no way to distinguish them, for example. And so, write your own adapter and, for example, try to parse it by brute force, to the victorious one.

A
Alexey Cheremisin, 2018-02-22
@leahch

In any case, there are at least two options, either to look ahead in the flow, or to rediscover.
You can do it in a tricky way - use https://docs.oracle.com/javase/7/docs/api/java/io/... and/or GSON stream API.
In the first case, we look into the stream for a certain size, look through it for the presence of the markers we need, then do unread and already work as we need.
In the second case, you can read only the first element, find the markers we need and, for example, reopen the file - https://memorynotfound.com/gson-streaming-api-read...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question