创建JSON android
我想要这样的输出创建JSON android,android,android-json,Android,Android Json,我想要这样的输出 {"content":{ "A":["a1","a2","a3"], "B":"b1String", "C":["c1","c2"]}} 到现在为止,我得到了这个 {"content":{ "A":"[a1, a2, a3]", "C":"[c1, c2]", "B":"b1String"}} 下面是我的代码 Map <String, Object> myMap = new HashMap<St
{"content":{
"A":["a1","a2","a3"],
"B":"b1String",
"C":["c1","c2"]}}
到现在为止,我得到了这个
{"content":{
"A":"[a1, a2, a3]",
"C":"[c1, c2]",
"B":"b1String"}}
下面是我的代码
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());
Map myMap=newhashmap();
myMap.put(“A”,arrayOfA)//哪个是ArrayList
myMap.put(“B”,myB1String)//哪个是字符串
myMap.put(“C”,arrayOfC)//哪个是ArrayList
JSONObject jsonAll=新的JSONObject(myMap);
Map mapAll=新的HashMap();
mapAll.put(“内容”,JSONAL);
JSONObject finalObject=新的JSONObject(mapAll);
Log.e(“JSON”,finalObject.toString());
任何帮助都将不胜感激。谢谢如果您想在
数组中显示它
,那么您需要在JSONArray
中添加所有字符串数组,并将其添加到对象中以将其显示为数组
示例:
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());
{"content":{"A":["a1","a2","a3"],"B":"b1String","C":["a1","a2","a3"]}}
试试这种方法,希望这能帮助你解决问题。
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"]}}
你查过我的电话号码了吗?