Skip level when parsing with Gson

I have json format:

{
"root": {
    "user": {
        "name":"Name",
        "age":99,
        "another_obj": {
            "f1":"abc",
            "f2":1
        }
    }
},
"result_code": 0
}

I am creating some model:

class User {
private String name;
private int age;
@SerializedName("detail")
private Detail
}

class Detail{
   // Define something.
}

Finally, I create the class name UserWapper.

class UserWapper {
@SerializedName("root")
private User user;  
}

To parse json:

String json = "STRING_JSON_ABOVE";
Gson gson = new Gson();
UserWrapper uw = gson.fromJson(json, UserWrapper.class);

But at the moment I do not want to create a Wrapper class. Because I have many classes. If you create a WrapperClass →: |

I want to do something like:

User u = gson.fromJson(json, User.class).

(Note: I can’t change the json format data from the server. I also looked for some custom gson adapter from gg, but I did not find a way to skip the “level” of another field).

+4
source share
2 answers

-, json JsonObject, user user.

:

String json = "{\"root\":{\"user\":{\"name\":\"Name\",\"age\":99,\"another_obj\":{\"f1\":\"abc\",\"f2\":1}}},\"result_code\":0}";
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
User u = gson.fromJson(((JsonObject)jsonObject.get("root")).get("user"), User.class);

System.out.println("user.name: " + u.name);
System.out.println("user.age: " + u.age);

:

_:
user.age: 99

+2

: JsonAdapter , -. JsonAdapter TypeAdapterFactory, :

/**
 * Use with {@link com.google.gson.annotations.JsonAdapter} on fields to skip a single pseudo object
 * for map-like types.
 */
public class UnwrappingJsonAdapter implements TypeAdapterFactory {

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
        return new TypeAdapter<T>() {

            @Override
            public void write(JsonWriter out, T value) throws IOException {
                out.beginObject();
                out.name(type.getType().getClass().getSimpleName());
                gson.toJson(value, type.getType(), out);
                out.endObject();
            }

            @Override
            public T read(JsonReader in) throws IOException {
                in.beginObject();
                in.nextName();
                final T object = gson.fromJson(in, type.getType());
                in.endObject();
                return object;
            }
        };
    }
}

. . , .

0

All Articles