Ho una struttura JSON che ho incollato qui sotto. Mi piacerebbe deserializzare il json in un POJO java usando Gson
che è piuttosto diretto, tranne che voglio mantenere uno dei campi, data
, come un tipo di stringa invece di un oggetto nidificato.Come posso deserializzare un oggetto JSON ma mantenere un campo specifico come stringa invece di un oggetto nidificato?
struttura JSON
{
"created_on": "2015-06-04T16:12:04-0700",
"modified_on": "2015-06-04T16:12:09-0700",
"identifier": "sample",
"name": "some name",
"summary": "some summary",
"data": {
"$type": "a_type",
"some_other_stuff": {
"more_stuff": "lorem ipsum"
},
"type2": {
"$type": "another_type",
"other_stuff": {
"event_more_stuff": "lorem ipsum"
}
}
}
}
mio POJO sarebbe quindi simile a questa:
public class Sample {
private String identifier; // "sample"
private String created_on; // "2015-06-04T16:12:04-0700"
private String modified_on; // "2015-06-04T16:12:09-0700"
private String name; // "some name"
private String summary; // "some summary"
private String data; // "{ \"$type\": ... }"
// getters and setters
}
Il campo data
deve rimanere come una stringa in formato JSON.
Ho provato a implementare un numero personalizzato TypeAdapter
e a leggere il campo come stringa, ma non riesce con Expected a string but was BEGIN_OBJECT
.
Inoltre, mi piacerebbe che la struttura venga mantenuta anche sulla serializzazione, così posso serializzare il POJO sulla struttura JSON originale.
Modifica personalizzato TypeAdapter
:
public class SampleTypeAdapter extends TypeAdapter<Sample> {
@Override
public void write(JsonWriter out, Sample sample) throws IOException {
out.beginObject();
out.name("identifier").value(sample.getIdentifier());
out.name("name").value(sample.getName());
out.name("data").value(sample.getData());
out.name("summary").value(sample.getSummary());
out.name("modified_on").value(sample.getModifiedOn());
out.name("created_on").value(sample.getCreatedOn());
out.endObject();
}
@Override
public Sample read(JsonReader in) throws IOException {
final Sample sample = new Sample();
in.beginObject();
while (in.hasNext()) {
String nextName = in.nextName();
switch (nextName) {
case "identifier":
sample.setIdentifier(in.nextString());
break;
case "name":
sample.setName(in.nextString());
break;
case "data":
sample.setData(in.nextString()); // <-- fails here
break;
case "summary":
sample.setSummary(in.nextString());
break;
case "modified_on":
sample.setModifiedOn(in.nextString());
break;
case "created_on":
sample.setCreatedOn(in.nextString());
break;
default:
in.skipValue();
break;
}
}
in.endObject();
return sample;
}
}
Potresti pubblicare il TypeAdapter personalizzato? – Cata