您的位置:首页 > Web前端 > JavaScript

json数据解析

2015-06-30 21:40 801 查看
<span style="font-size:18px;">package com.example.json_test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
private TextView  myview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.myview=(TextView)super.findViewById(R.id.myview);
StringBuffer buf=new StringBuffer();
String str = "[{\"id\":1,\"name\":\"lixinghua\",\"age\":30},"
+ "{\"id\":2,\"name\":\"MLDN\",\"age\":10}]";
try {
List<Map<String, Object>> all=this.praseJson(str);//与下面的方法操作
//调用下面的方法,类型为泛型
Iterator<Map<String , Object>> iter=all.iterator();//创建一个对象,
//进行map迭代,这里把map看做是一个数组
while(iter.hasNext()){//进行迭代,输入到buf对象中
Map<String ,Object>map=iter.next();
buf.append("id"+map.get("id")+",xingming"+map.get("name")+
",nianling"+map.get("age"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
this.myview.setText(buf);//设置文本
}
}
public  List<Map<String ,Object>> praseJson (String data) throws JSONException{
//list泛型方法,生成一个对象利用子类接口生成一个对象
List<Map<String ,Object>> all=new ArrayList<Map<String,Object>>();
JSONArray jsonArr =new JSONArray(data);
//对上面的json解析后的data数组数据进行操作,
for (int i=0;i<jsonArr.length();i++){
Map<String, Object> map=new HashMap<String, Object>();
JSONObject jsonObj= jsonArr.getJSONObject(i);
map.put("id", jsonObj.getInt("id"));
map.put("name", jsonObj.get("name"));
map.put("age", jsonObj.getInt("age"));
all.add(map);
};
return null;
}
}
</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: