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;
publicclassKey {
@SerializedName("key")
privateString key;
publicStringgetKey() {
return key;
}
publicvoidsetKey(String key) {
this.key = key;
}
}
Data.java
import java.util.ArrayList;
import com.google.gson.annotations.SerializedName;
publicclassData {
@SerializedName("someName")
privateString someKey;
@SerializedName("Key")
privateKey key;
@SerializedName("keys")
privateArrayList<Key> keys;
publicStringgetSomeKey() {
return someKey;
}
publicvoidsetSomeKey(String someKey) {
this.someKey = someKey;
}
publicKeygetKey() {
return key;
}
publicvoidsetKey(Key key) {
this.key = key;
}
publicArrayList<Key> getKeys() {
return keys;
}
publicvoidsetKeys(ArrayList<Key> keys) {
this.keys = keys;
}
}
you can test this with following code
publicstaticvoidmain(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"