Skip to content Skip to sidebar Skip to footer

GSON Deserialize To Bundle

How can i deserialize this JSON: 'data': { 'key1': 11, 'key2': { 'key3': 22 'key4': 83 'key5': 99 } } to an Android Bundle using GSON library?

Solution 1:

ok, I can write an example to this likeness to your question..

I believe your keys would be changing as what you have asked in the question is not the same as what you actually want, so I created a Key class and you can change it to appropriate class Object which you need to get.

Key.java

import com.google.gson.annotations.SerializedName;

public class Key {

    @SerializedName("key")
    private String key;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}

Data.java

import java.util.ArrayList;

import com.google.gson.annotations.SerializedName;

public class Data {

    @SerializedName("someName")
    private String someKey;

    @SerializedName("Key")
    private Key key;

    @SerializedName("keys")
    private ArrayList<Key> keys;

    public String getSomeKey() {
        return someKey;
    }

    public void setSomeKey(String someKey) {
        this.someKey = someKey;
    }

    public Key getKey() {
        return key;
    }

    public void setKey(Key key) {
        this.key = key;
    }

    public ArrayList<Key> getKeys() {
        return keys;
    }

    public void setKeys(ArrayList<Key> keys) {
        this.keys = keys;
    }
}

you can test this with following code

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Key key = new Key();
    key.setKey("someNumber");

    ArrayList<Key> keys = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
        Key key2 = new Key();
        key2.setKey("1"+i);
        keys.add(key2);
    }

    Data data = new Data();
    data.setKey(key);
    data.setKeys(keys);

    String result =(new Gson()).toJson(data);

    System.out.println(result);

    System.out.println("\n#######\n");

    Data data2 = (new Gson()).fromJson(result, Data.class);

    System.out.println(data2.getKey().getKey());
}

this is just an example where the class Data has been converted in JSON and than deserialized to get it's object populated, this should get you an idea about how to read your own data.

Output

{"Key":{"key":"someNumber"},"keys":[{"key":"10"},{"key":"11"},{"key":"12"},{"key":"13"},{"key":"14"}]}

#######

someNumber
10
11
12
13
14

Post a Comment for "GSON Deserialize To Bundle"