0

I want to have an output like this

{"content":{
     "A":["a1","a2","a3"],
     "B":"b1String",
     "C":["c1","c2"]}}

As of now, I am getting this.

{"content":{
     "A":"[a1, a2, a3]",
     "C":"[c1, c2]",
     "B":"b1String"}}

Below is my code

Map <String, Object> myMap =  new HashMap<String, Object>();

myMap.put("A",arrayOfA); //which is ArrayList<String>
myMap.put("B", myB1String);//which is String
myMap.put("C", arrayOfC);//which is ArrayList<String>

JSONObject jsonAll = new JSONObject(myMap);

Map <String, Object> mapAll =  new HashMap<String, Object>();
mapAll.put("content", jsonAll);

JSONObject finalObject=new JSONObject(mapAll);
Log.e("JSON", finalObject.toString());

Any help woulld be much appreciated. Thanks

1
  • have you check my ans ? Commented Aug 1, 2014 at 6:04

2 Answers 2

1

If you want to display it in an array then you need to add all your string arrays in a JSONArray and add it to the object to display it as an array.

sample:

    JSONArray s2 = new JSONArray();
    s2.put("a1");
    s2.put("a2");
    s2.put("a3");

    myMap.put("A",s2); //which is ArrayList<String>
    myMap.put("B", "b1String");//which is String
    myMap.put("C", s2);

    //which is ArrayList<String>

    JSONObject jsonAll = new JSONObject(myMap);

    Map <String, Object> mapAll =  new HashMap<String, Object>();
    mapAll.put("content", jsonAll);

    JSONObject finalObject=new JSONObject(mapAll);
    Log.d("JSON", finalObject.toString());

result:

{"content":{"A":["a1","a2","a3"],"B":"b1String","C":["a1","a2","a3"]}}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this way,hope this will help you to solve your problem.

String[] stringArrayOfA = new String[]{"a1","a2","a3"};
String[] stringArrayOfC = new String[]{"c1","c2"};

try {
    JSONArray jsonArrayA = new JSONArray();
    for (String str : stringArrayOfA){
        jsonArrayA.put(str);
    }
    JSONArray jsonArrayC = new JSONArray();
    for (String str : stringArrayOfC){
        jsonArrayC.put(str);
    }
    JSONObject innerJsonobject = new JSONObject();
    innerJsonobject.put("A",jsonArrayA);
    innerJsonobject.put("B","b1String");
    innerJsonobject.put("C",jsonArrayC);
    JSONObject outerJsonObject = new JSONObject();
    outerJsonObject.put("content",innerJsonobject);
    Log.e("JSON", outerJsonObject.toString());
} catch (JSONException e) {
    e.printStackTrace();
}

Result :{"content":{"A":["a1","a2","a3"],"B":"b1String","C":["c1","c2"]}}

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.