0

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

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the answer, very elucidative
@Guilherme Please mark the answer as "Accepted" if it has solved your issue.
@Mangesh Done. Could you help me with one more thing? I'm not sure how I'll pass all these Lists through my AsyncTask to become String... params
@Guigs You only need to pass one Foo object or one JSONObject class. new WebTask().execute(obj);... Or, instead you can use Volley or Retrofit, which are easier to mess with than AsyncTask once you learn them
0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.