Android-创建JSON数组和JSON对象 [英] Android- create JSON Array and JSON Object
本文介绍了Android-创建JSON数组和JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何创建一个JSON这个格式的Android版本: 从那时起,我将通过将解析JsonArray那么对象的API。 还是会好起来的,如果只是为了传递一个JSON对象?因为我只需要插入每个服务呼叫的1交易。
How can I create a JSON with this format in Android: Since the API that I will be passing will parse JsonArray then the object. Or would it be okay if just to pass a json object? Since I will just have to insert 1 transaction per service call.
{
"student": [
{
"id": 1,
"name": "John Doe",
"year": "1st",
"curriculum": "Arts",
"birthday": 3/3/1995
},
{
"id": 2,
"name": "Michael West",
"year": "2nd",
"curriculum": "Economic",
"birthday": 4/4/1994
}
]
}
我所知道的只是的JSONObject。 赞一个。
What I know is only the JSONObject. Like this one.
JSONObject obj = new JSONObject();
try {
obj.put("id", "3");
obj.put("name", "NAME OF STUDENT");
obj.put("year", "3rd");
obj.put("curriculum", "Arts");
obj.put("birthday", "5/5/1993");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
任何想法。谢谢
Any ideas. Thanks
推荐答案
使用下面的code:
JSONObject student1 = new JSONObject();
try {
student1.put("id", "3");
student1.put("name", "NAME OF STUDENT");
student1.put("year", "3rd");
student1.put("curriculum", "Arts");
student1.put("birthday", "5/5/1993");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject student2 = new JSONObject();
try {
student2.put("id", "2");
student2.put("name", "NAME OF STUDENT2");
student2.put("year", "4rd");
student2.put("curriculum", "scicence");
student2.put("birthday", "5/5/1993");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(student1);
jsonArray.put(student2);
JSONObject studentsObj = new JSONObject();
studentsObj.put("Students", jsonArray);
String jsonStr = studentsObj.toString();
System.out.println("jsonString: "+jsonStr);
这篇关于Android-创建JSON数组和JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文