Satchmo
Satchmo

Reputation: 99

Read nested json objects that have been serialized via gson library

I am storing an object in shared preferences. To do this I am serializing the object using the gson library and a typeadapter before storing them.

Here's what my object looks like in json:

    {
    "id": 0,
    "name": "Sensor 2D:D3:5C",
    "address": "00:07:80:2D:D3:5C",
    "device": {
    "mAddress": "00:07:80:2D:D3:5C"
    },
    "temp": "31342e37"
    }

This all works, but not when deserializing the "device" because it is a BluetoothDevice object instead of a simple string or int value. How can I tell my TypeAdapter to properly deserialize this?

Here's a look at the read method of my typeadapter:

    @Override
    public myDevice read(final JsonReader in) throws IOException {
        final myDevice dv= new myDevice();
        in.beginObject();
        while (in.hasNext()) {
            switch (in.nextName()) {
                case "id":
                    dv.setId(in.nextInt());
                    break;
                case "name":
                    dv.setName(in.nextString());
                    break;
                case "address":
                    dv.setAddress(in.nextString());
                    break;
                case "temp":
                    dv.setTemp(in.nextString());
                    break;
                case "device":
                    //What do I do here??
                    //dv.setDevice(in.????);
                    break;
            }
        }
        in.endObject();
        return vd;
    }

Upvotes: 0

Views: 197

Answers (1)

Alban Dericbourg
Alban Dericbourg

Reputation: 1634

Is there a reason to use a TypeAdapter instead of mapping directly the JSON into an object? For instance with:

Gson gson = new Gson();
Info info = gson.fromJson(jsonString, Info.class)

If you need to use the JsonReader, then you could consider using JsonToken by calling reader.peek(). You will then be able to switch over token types (BEGIN_OBJECT, END_OBJECT, BEGIN_ARRAY, STRING...).

Upvotes: 1

Related Questions