Reputation: 25
I need to produce a JSON with many objects inside, and each of them to have an array of strings. I'm using Java, more specifically Android.
I want to produce something like the following:
"manager1": [
{"product1":"xxxx"},
{"product2":"yyyy"},
{"product3":"zzzz"}
],
"manager2": [
{"product1":"xxxx"},
{"product2":"yyyy"},
{"product3":"zzzz"}
]
I have a Bean class which has this manager and array of products information, am just having trouble to see how that would fit inside my AsyncTask class
Upvotes: 0
Views: 62
Reputation: 444
If you have objects you can use Gson library to convert object into json string.
Gson gson = new Gson();
String json = gson.toJson(obj);
If you ask about structure of classes in your Java code it will be the Map of the android.util.Pair arrays.
Map<String, Pair<String, String>[]> map;
But.... you have to create your own serializer and deserializer for Pair class. The answer you can find here: How do I get Gson to serialize a list of basic name value pairs?
Upvotes: 0
Reputation: 191983
I would recommend not appending numbers to your keys. That just messes up your java classes.
Use lists for everything.
{
"managers": [
{
"name": "manager1",
"products": ["xxx", "yyy", "zzz"]
},
{
"name": "manager2",
"products": ["xxx", "yyy", "zzz"]
}
]
}
You POJOs / beans would look like so
class Foo {
List<Manager> managers;
}
class Manager {
String name;
List<String> products;
}
Upvotes: 1