I’m using the Gson library in Java to serialize java objects to jSon and vice versa.
It works pretty well most of the times…but because I want to access my collections in javascript as mapped arrays I need to send them as properties and not json arrays.
For instance lets assume I have a Group which has several persons in it…if I send it:
var groups={"group1":[{"john":{"age":22,"sex":"male"}},{"patricia":{"age":32,"sex":"female"}}]}
I can’t do groups[“group1”][“john”]…and I’ll have to iterate through the array to find the correct person.
But if I do:
var groups={"group1":{"john":{"age":22,"sex":"male"},"patricia":{"age":32,"sex":"female"}}}
now I can do groups[“group1”][“john”].
The problem with this is that the Group has an Array of Person and when gson serializes to json it puts each person as an array element [{…and not as an property of group1 which in turn is a property of groups.
I’d like to know if it’s possible to tell gson to serialize to mapped arrays instead of normal arrays. If so how.
Don’t use an array if you don’t want an array.
If you change to using a
Mapin java it should serialize to your second example:(The keys to the
HashMapare your people’s names)