Answer the question
In order to leave comments, you need to log in
How to make a class for working with JSON, which can contain objects of different types?
From the server API comes a JSON of the form
{
'field1':'<string>',
'field2':'string','
list':[{
'id':'123',
'uid':'123',
'date':'<datetime dd.mm.yyyy hh:mi:ss>',
'msg':{<message в json формате>}},...
], ...}
Answer the question
In order to leave comments, you need to log in
With retrofit, you are probably using some kind of ConverterFactory to convert the response to an object. For example, GsonConverterFactory (GSON). Consider the situation on his example:
You describe all objects as usual, except for msg. You describe it as the Message interface. Register:
class MessageDeserializer implements JsonDeserializer<Message>{ ... }
...
Gson gson = new GsonBuilder()
.registerTypeAdapter(Message.class, new MessageDeserializer())
.create();
GsonConverterFactory.create(gson);
public Message deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { ... }
class MessageTxt implements Message {
private final String txt;
public MessageTxt(String txt){
this.txt = txt;
}
String getTxt() { return txt; }
}
Isn't the entire response in json format just a string?
Well, depending on how you process, you already extract the data of the desired format.
I don't know how in java, but in python it looks like this:
import sys
import json
response = json.loads(sys.stdin.read())
field1 = response['field1'] #'строка'
lst = response['list']['id'] # '123' - по сути это тоже строка, ибо числа в python без кавычек
если нужно получить число, то можно явно преобразовать в число
lst = int(lst)
или так, если не знаешь число или не число:
try:
lst = int(lst)
except ValueError:
print "преобразовать не получилось"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question