Reputation: 2106
I have a json file which has following structure:
{
"Otions": true
"Plastic": ""
"Houses": {
7: {
"name": "Akash Bhawan"
"MemBers": 3
"children": 1
}-
8: {
"name": "Ashiyana"
"memBers": 4
"children": 2
}-
9: {
"name": "Faruks Nest"
"memBers": 5
"children": 1
}-
The objects inside Houses are variable and can increase or decrease accordingly and also change names. How ever the fieds "name", "members", "children" are the only fields and will always be there
i am using gson to parse
@SerializedName("Otions")
private String Options;
@SerializedName("Plastic")
private String plastics;
@SerializedName("Houses")
private Houses houses;
i want to know if there is a way we can i can store differently named objects in a hashtable or some other way?
Upvotes: 0
Views: 1211
Reputation: 6555
You should do something like (as said in my comment):
JSONObject jsonHouses = jsonObject.getJSONObject("Houses");
Iterator<String> keys = jsonHouses.keys(); //this will be array of "7", "8", "9"
if (keys.hasNext()) {
JSONObject singleHouseObject = jsonHouses.getJSONObject(keys.next());
//now do whatever you want to do with singleHouseObject.
//this is the object which has "name", "MemBers", "children"
}
Upvotes: 0
Reputation: 1921
If you can't change the structure then you have to make house as Hashmap
of int
to object
. For Example:-
HashMap<int, Object> House;
And that object will have elements like name, memBers, details.
Upvotes: 1
Reputation: 663
Please make "house" as bunch of array instead of objects.
{
"Options": true,
"Plastics": "",
"house": [{
"name": "Akash Bhawan",
"MemBers": 3,
"children": 1
}, {
"name": "Ashiyana",
"memBers": 4,
"children": 2
}, {
"name": "Faruks Nest",
"memBers": 5,
"children": 1
}]
}
Upvotes: 0
Reputation: 2117
Houses should be a map like this.
private HashMap houses.
Since the 3: indicates an index-structure. Gson will create the nested objects as needed.
Upvotes: 0