JSON数据解析

来源:互联网 发布:rpm yum 区别 编辑:程序博客网 时间:2024/05/29 16:04

       JSON:一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案,从而可以在不同平台间进行数据交换。JSON采用完全独立于语言平台的文本格式,使用JSON可以将对象中的一组数据转换成字符串,然后可以在各个应用程序之间传递这些字符串,或者在异步系统中进行服务器与客户端之间的数据传递。Android系统中,JSON操作所需要的数据包已经默认集成了。如下代码为JSON的数据解析,生成txt文档:

 public class MyDemo extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
String data[] = new String[] { "www.baidu.com", "jackiewang",
"window of world" };  //要輸出的數據
JSONObject allData=new JSONObject();  //建立最外面的節點對象
JSONArray sing=new JSONArray();  //定義數組
for(int x=0;x<data.length;x++){
JSONObject temp=new JSONObject(); //每一個包裝的數據都是JSONObect
try {
temp.put("myurl", data[x]);
} catch (JSONException e) {
e.printStackTrace();
}
sing.put(temp); //保存多個JSONObject
}
try {
allData.put("urldata",sing);
} catch (JSONException e) {
e.printStackTrace();
}
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return;// 不存在不操作
}
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "myinfo" + File.separator + "json.txt");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
PrintStream out=null;
try {
out=new PrintStream(new FileOutputStream(file));
out.print(allData.toString()); //將數據變成字符串后保存
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
if(out!=null){
out.close();
}
}
}

解析JSON的数据,并显示在textView上,这个parseJson()方法主要对解析功能的封装,这个实例只有数组

public class MyDemo extends Activity {
private TextView msg = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
this.msg = (TextView) super.findViewById(R.id.msg);
String str = "[{\"id\":1,\"name\":\"施耐庵\",\"age\":30},"
+ "{\"id\":2,\"name\":\"jackie\",\"age\":23}]";
StringBuffer buf = new StringBuffer();
try {
List<Map<String, Object>> all = this.parseJson(str);
Iterator<Map<String, Object>> iter = all.iterator();
while (iter.hasNext()) {
Map<String, Object> map = iter.next();
buf.append("ID:" + map.get("id") + ",姓名:" + map.get("name")
+ ",年龄:" + map.get("age") + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
this.msg.setText(buf);
}


private List<Map<String, Object>> parseJson(String data) throws Exception {
List<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
JSONArray jsonarray = new JSONArray(data); // data是数组,需创建数组对象
for (int x = 0; x < jsonarray.length(); x++) {
Map<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObj = jsonarray.getJSONObject(x);       //json的元素与元素值,基本类型
map.put("id", jsonObj.getInt("id"));
map.put("name", jsonObj.getString("name"));
map.put("age", jsonObj.getInt("age"));
all.add(map);
}
return all;
}
}

下面实例增加了个项,复杂的json文件解析也是JSONObject和JSONArray的相互嵌套

public class MyDemo extends Activity {
private TextView msg = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
this.msg = (TextView) super.findViewById(R.id.msg);
String str = "{\"memberdata\":[{\"id\":1,\"name\":\"施耐庵\",\"age\":30},"
+ "{\"id\":2,\"name\":\"jackie\",\"age\":23}],\"company\":\"北京百度科技公司\"}";
StringBuffer buf = new StringBuffer();
try {
Map<String, Object> allMap = this.parseJson(str);
buf.append("公司:"+allMap.get("company")+"\n");
List<Map<String,Object>> all=(List<Map<String,Object>>) allMap.get("memberdata");
Iterator<Map<String, Object>> iter = all.iterator();
while (iter.hasNext()) {
Map<String, Object> map = iter.next();
buf.append("ID:" + map.get("id") + ",姓名:" + map.get("name")
+ ",年龄:" + map.get("age") + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
this.msg.setText(buf);
}


private Map<String, Object> parseJson(String data) throws Exception {
Map<String, Object> allMap = new HashMap<String, Object>();
JSONObject allData=new JSONObject(data);   //全部的内容变成一个项
allMap.put("company",allData.getString("company"));
JSONArray jsonarray = allData.getJSONArray("memberdata");//取出数组
List<Map<String,Object>> all=new ArrayList<Map<String,Object>>();
for (int x = 0; x < jsonarray.length(); x++) {
Map<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObj = jsonarray.getJSONObject(x);
map.put("id", jsonObj.getInt("id"));
map.put("name", jsonObj.getString("name"));
map.put("age", jsonObj.getInt("age"));
all.add(map);
}
        allMap.put("memberdata", all);
return allMap;
}
}
0 0
原创粉丝点击