当前位置: 动力学知识库 > 问答 > 编程问答 >

android - 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? This is not working:

class Model implements Parcelable {

private int key1;

private Bundle key2;

[...]

protected Model(Parcel in) {

key1 = in.readInt();

[...]

key2 = in.readBundle();

}

public void writeToParcel(Parcel dest, int flags) {

dest.writeInt(key1);

[...]

dest.writeBundle(key2);

}

}

I don't want to create a key2 model.

网友答案:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: