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>
相关文章推荐
- [Javascript + rxjs] Simple drag and drop with Observables
- bzoj1016 [JSOI2008]最小生成树计数
- Javascript——表单提交
- JSP语法简介
- javascript入门教程笔记
- 后台传值让select默认加载到对应的选项的解决方法(EJS)
- json转json树状结构
- Thrift之TProtocol系列TJSONProtocol解析
- 第一个JSP程序(JSP入门)
- 在JS函数中执行C#中的函数、字段
- javascript unshift()和shift()
- 常用JS图片滚动(无缝、平滑、上下左右滚动)代码大全
- js操作string它substr方法
- JS图片滚动代码(无缝、平滑)
- JS漂浮广告代码
- 【 D3.js 高级系列 】 总结
- javascript中冒泡事件和阻止默认事件
- 【 D3.js 高级系列 】 总结
- 深入Javascript函数与闭包(执行环境、变量对象与作用域链)使用详解
- javascript基础