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

Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
kads
  • 112
  • 1
  • 10

2 Answers2

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"]}}
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
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"]}}
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67