json有四种行式1 简单的一个 { ,,,,}
2 里面有数组 { , [{,,},{,,}],}
3 直接一个数组
4 数组里有数组
package com.example.jsontest; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.os.Bundle; public class MainActivity extends ActionBarActivity { private ArrayList<Ping> data = new ArrayList<Ping>(); private ArrayList<Ping> data1 = new ArrayList<Ping>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addData(); JSONObject json = new JSONObject(); JSONArray ja = new JSONArray(); JSONArray ja1 = new JSONArray(); for( Ping a : data){ //把list里的值转OBJECT JSONObject obj = new JSONObject(); try { obj.put("id", a.getA()); obj.put("name", a.getName()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } ja.put(obj);//把object加入到JSONArray } for( Ping a : data1){ JSONObject obj = new JSONObject(); try { obj.put("id", a.getA()); obj.put("name", a.getName()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } ja1.put(obj); } try { json.put("data", ja); //把JSONArray加入JSONObject json.put("data1", ja1); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Log.e("", json.toString()); json(json.toString()); } private void json(String a){ try { JSONObject obj = new JSONObject(a); JSONArray jsonArray = obj.getJSONArray("data"); JSONArray jsonArray1 = obj.getJSONArray("data1"); for (int i = 0; i <jsonArray.length(); i++) { JSONObject jsonObj = jsonArray.getJSONObject(i); String name =jsonObj.getString("name"); String id = jsonObj.getString("id"); Log.e("", name +"--"+id); } for (int i = 0; i <jsonArray1.length(); i++) { JSONObject jsonObj = jsonArray1.getJSONObject(i); String name1 =jsonObj.getString("name"); String id1 = jsonObj.getString("id"); Log.e("", name1 +"--"+id1); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void addData() { for (int i = 0; i < 10; i++) { Ping item = new Ping(); item.setA(i); item.setName("小明"+i); data.add(item); } for (int i = 0; i < 10; i++) { Ping item = new Ping(); item.setA(i); item.setName("小红"+i); data1.add(item); } } }package com.example.jsontest; public class Ping { private String name; private int a; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getA() { return a; } public void setA(int a) { this.a = a; } }
json数据的解析和把数据转换成json格式的字符串
最新推荐文章于 2022-03-30 03:40:51 发布