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

Json数据解析

2015-09-27 14:46 609 查看
JSON是什么?



JSON(JavaScript Object
Notation) 是一种轻量级的数据交换格式。它基于


ECMAScript的一个子集。
JSON采用完全独立于语言的文本格式,但是也使用了类似




于C语言家族的习惯(包括C、C++、C#Java、JavaScript、PerlPython等)。这



些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和



生成(网络传输速率)。



JSON实际用途

像百度翻译,百度语音识别的结果都是通过JSON反馈给我们的,所以,我们只需要解



析JSON数据,并且挑拣出我们需要的就可以把数据呈现给用户!











具体实现方式



1.JSON的创建

JSONObject student =new JSONObject();//创建student对象
try {
student.put("class",12);//加入班级
JSONObject s1=new JSONObject();
s1.put("id",10);
s1.put("name","liuchen");
s1.put("sex","male");
JSONObject s2=new JSONObject();
s2.put("id",11);
s2.put("name","xiaoming");
s2.put("sex","male");
JSONObject s3=new JSONObject();
s3.put("id",12);
s3.put("name","xiaohong");
s3.put("sex","female");//创建三个student对象
JSONArray array=new JSONArray();
array.put(s1);
array.put(s2);
array.put(s3);
student.put("students",array);
TextView tx1=(TextView)findViewById(R.id.tx1);
tx1.setText(student.toString());
} catch (JSONException e) {
e.printStackTrace();
}


这是运行效果图!

2.JSON的解析
创建assets文件夹,且创建text.json文件,向其中写入刚才输出的数据




try {
InputStreamReader isr= new InputStreamReader(getAssets().open("test.json"),"UTF-8");//打开文件
BufferedReader br =new BufferedReader(isr);//进一步包装
String line;
StringBuilder sb=new StringBuilder();//定义一个stringbuild
while((line=br.readLine())!=null){
sb.append(line);
}
br.close();
isr.close();
JSONObject jb=new JSONObject(sb.toString());
System.out.println("class="+jb.getString("class"));
JSONArray array =jb.getJSONArray("students");
for(int i=0;i<array.length();i++){
JSONObject student=array.getJSONObject(i);
System.out.println("id="+student.getInt("id")+"name="+student.getString("name")+"sex="+student.getString("sex"));
}
}
catch (Exception e){
e.printStackTrace();
}



解析成功!
















内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  安卓基础知识