json数据的解析和把数据转换成json格式的字符串

来源:互联网 发布:域名要备案才能解析吗 编辑:程序博客网 时间:2024/05/27 09:44
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>();@Overrideprotected 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里的值转OBJECTJSONObject obj = new JSONObject();try {obj.put("id", a.getA()); obj.put("name", a.getName());} catch (JSONException e) {// TODO Auto-generated catch blocke.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 blocke.printStackTrace();}ja1.put(obj);}try {json.put("data", ja); //把JSONArray加入JSONObjectjson.put("data1", ja1);} catch (JSONException e) {// TODO Auto-generated catch blocke.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 blocke.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;}}
0 0
原创粉丝点击