json 的解析-使用Android中的JSONObject和JSONArray解析json数据

1、代码

public class MainActivity extends Activity {
TextView tv_json;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_json = (TextView) findViewById(R.id.tv_json);
JSONObject jsonObject = new JSONObject();//往里面put数据
JSONArray ja = new JSONArray();//将JsonObject对象放入
JSONObject jsonObject2 = new JSONObject();//往里面put数据
JSONArray ja2 = new JSONArray();//将JsonObject对象放入
JSONObject jsonInfo = new JSONObject();//存放jsonArray数据  实现key-value


try {
jsonObject.put("name", "tom");
jsonObject.put("password", "123");
jsonObject.put("sex", "man");
jsonObject.put("age", "20");
jsonObject2.put("name2", "tom");
jsonObject2.put("password2", "123");
jsonObject2.put("sex2", "man");
jsonObject2.put("age2", "20");
ja.put(jsonObject);
ja2.put(jsonObject2);
jsonInfo.put("first", ja);
jsonInfo.put("second", ja2);
            System.out.println("jsoninfo==="+jsonInfo.toString());
tv_json.setText("sum===" + jsonInfo.toString());
JSONObject getJson = new JSONObject(jsonInfo.toString());
JSONArray jArray=(JSONArray) getJson.get("first");
for(int i=0;i<jArray.length();i++){
JSONObject o=(JSONObject) jArray.get(i);
System.out.println("o.name==="+o.getString("name"));
}


} catch (JSONException e) {
e.printStackTrace();
}


}


}

2、输出结果:

jsoninfo==={"second":[{"age2":"20","sex2":"man","name2":"tom","password2":"123"}],"first":[{"password":"123","sex":"man","age":"20","name":"tom"}]}

o.name===tom


2.2、json数据 ,无序

{
  "second": [
    {
      "age2": "20",
      "sex2": "man",
      "name2": "tom",
      "password2": "123"
    }
  ],
  "first": [
    {
      "password": "123",
      "sex": "man",
      "age": "20",
      "name": "tom"
    }
  ]
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值