This is almost the same question as How do I deserialize Json with modifying the structure?, except your json structure is different. Please read the explanation there for more details. If your examples are more complicated than the one you've provided in the question, read that full answer to see how to modify it further.
You can use this TypeAdapter<Person>
to do the parsing you want:
import java.io.IOException;
import com.google.gson.*;
import com.google.gson.stream.*;
public class PersonTypeAdapter extends TypeAdapter<Person> {
@Override
public void write(JsonWriter out, Person value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
out.nullValue();
// exercise for you, if you even need it
}
@Override
public Person read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
reader.beginObject();
validateName(reader, "name");
String name = reader.nextString();
validateName(reader, "address");
reader.beginObject();
validateName(reader, "addressName");
String addressName = reader.nextString();
validateName(reader, "addressList");
reader.beginArray();
reader.beginObject();
validateName(reader, "State");
String addressState1 = reader.nextString();
validateName(reader, "City");
String addressCity1 = reader.nextString();
reader.endObject();
reader.beginObject();
validateName(reader, "State");
String addressState2 = reader.nextString();
validateName(reader, "City");
String addressCity2 = reader.nextString();
reader.endObject();
reader.endArray();
reader.endObject();
reader.endObject();
return new Person(name, addressName,
addressState1, addressCity1,
addressState2, addressCity2);
}
private void validateName(JsonReader reader, String string) throws IOException {
String name = reader.nextName();
if(!string.equals(name)) {
throw new JsonSyntaxException("Expected: \"" + string + "\", got \"" + name + "\"");
}
}
}
Then, just register this with your GsonBuilder
:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Person.class, new PersonTypeAdapter());
Gson g = builder.create();
Person person = g.fromJson(jsonString, Person.class);