移动开发与后台数据的交互至关重要,开始:
demo运行效果:
1. JSON数据的组装
示例:
{
“name”:”xxx”,
“gender”:”男”,
“age”:”15”,
“grilFriend”:[“小美”,”小花”],
“like”:{
“eat”:”banana”,”look”:”running man”
},
“boy”:[{“女神”:”美女”,”偶像”:”梅西”},{“弟弟”:”小逗逼”,”哥哥”:”大逗逼”}]
}
代码:
JSONObject jsonObject = new JSONObject();
try {
//姓名
jsonObject.put("name", "蜘蛛人");
//性别
jsonObject.put("gender", "男");
//年龄
jsonObject.put("age", 32);
//朋友(数组形式)
JSONArray gril = new JSONArray();
gril.put("小花");
gril.put("小美");
jsonObject.put("grilFriend", gril);
//爱好
JSONObject like = new JSONObject();
like.put("eat", "banana");
like.put("look", "running man");
jsonObject.put("like", like);
//json中的object
JSONArray boy = new JSONArray();
JSONObject childer = new JSONObject();
childer.put("偶像", "梅西");
childer.put("女神", "美女");
boy.put(0, childer);
JSONObject brother = new JSONObject();
brother.put("哥哥", "大逗逼");
brother.put("弟弟", "小逗逼");
boy.put(1, brother);
jsonObject.put("boy", boy);
JSON数据的解析
解析上面自己组装的JSON文本:
JSONObject jsonObject = JsonData.createJson();//获取json文本
jsonObject.getString(“name”);
jsonObject.getString(“gender”);
jsonObject.getInt(“age”);
jsonObject.getString(“grilFriend”);
JSONArray grilArray = jsonObject.getJSONArray(“grilFriend”);
jsonObject.getString(“like”);
JSONObject likeObject = jsonObject.optJSONObject(“like”);
likeObject.getString(“look”);
likeObject.getString(“eat”);JSONArray boyArray = jsonObject.getJSONArray("boy"); JSONObject boyObject = boyArray.optJSONObject(0); String star = boyObject.getString("偶像"); String goddess = boyObject.getString("女神"); JSONObject brotherObject = boyArray.optJSONObject(1); String oldBrother = brotherObject.getString("哥哥");
全部代码:
JSON文本:JsonData.java
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by czc.
*/
public class JsonData {
public static JSONObject createJson() {
JSONObject jsonObject = new JSONObject();
try {
//姓名
jsonObject.put("name", "蜘蛛人");
//性别
jsonObject.put("gender", "男");
//年龄
jsonObject.put("age", 32);
//朋友