JSON解析详解
- package com.jun.json;
-
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.URL;
-
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.util.EntityUtils;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import org.json.JSONTokener;
-
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- import android.widget.TextView;
-
- public class JsonActivity extends Activity {
-
-
- TextView tvJson=null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_json);
-
- tvJson=(TextView) findViewById(R.id.showTxt);
-
-
- jsonOper();
-
-
- }
- private void jsonOper() {
- // TODO Auto-generated method stub
- String str=connServerForResult("http://bcs.duapp.com/weimeipicture/tes.txt");
-
-
- parseJsonMulti(str);
- }
- /解析多个数据的Json
- private void parseJsonMulti(String strResult) {
-
- String sb ="";
- try {
-
- // JSONObject jsonObject=new JSONObject();
- // jsonObject.optJSONObject(strResult);
- // System.out.println("Jsons parse error 1");
- // JSONArray jsonObjs =jsonObject.getJSONArray("messages");
-
-
-
- JSONTokener jsonParser = new JSONTokener(strResult);
- JSONObject jsonObject = (JSONObject) jsonParser.nextValue();
- JSONArray jsonObjs =jsonObject.getJSONArray("messages");
-
- for(int i = 0; i < jsonObjs.length() ; i++){
- JSONObject jsonObj = ((JSONObject)jsonObjs.opt(i)) ;
-
- System.out.println("Jsons parse error 0"+i);
-
-
-
- String msg = jsonObj.getString("msg");
-
-
- sb+= "msg:::"+msg + "\n";
-
-
- System.out.println(sb);
-
-
-
- }
- tvJson.setText(sb);
- } catch (JSONException e) {
- System.out.println("Jsons parse error !!!!");
- e.printStackTrace();
- }
- }
-
- //获取json文本
- private String connServerForResult(String strUrl) {
- // HttpGet对象
- HttpGet httpRequest = new HttpGet(strUrl);
- String strResult = "";
- try {
- // HttpClient对象
- HttpClient httpClient = new DefaultHttpClient();
- // 获得HttpResponse对象
- HttpResponse httpResponse = httpClient.execute(httpRequest);
- if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- // 取得返回的数据
- strResult = EntityUtils.toString(httpResponse.getEntity());
- // str=new String(str.getBytes("8859_1"),"GB2312");
- //tvJson.setText();
-
-
-
- }
- } catch (ClientProtocolException e) {
- tvJson.setText("protocol error");
- e.printStackTrace();
- } catch (IOException e) {
- tvJson.setText("IO error");
- e.printStackTrace();
- }
-
- try {
- strResult=new String(strResult.getBytes("8859_1"),"GB2312");
- } catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return strResult;
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.activity_json, menu);
- return true;
- }
- }
注意:JAVA在网络传输中使用的编码是"ISO-8859-1",故在输出时需要进行转化,即: tvJson.setText(new String(strResult.getBytes("8859_1"),"GB2312"));
JSON的定义:
- package com.jun.json;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.util.EntityUtils;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import org.json.JSONTokener;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- import android.widget.TextView;
- public class JsonActivity extends Activity {
- TextView tvJson=null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_json);
- tvJson=(TextView) findViewById(R.id.showTxt);
- jsonOper();
- }
- private void jsonOper() {
- // TODO Auto-generated method stub
- String str=connServerForResult("http://bcs.duapp.com/weimeipicture/tes.txt");
- parseJsonMulti(str);
- }
- /解析多个数据的Json
- private void parseJsonMulti(String strResult) {
- String sb ="";
- try {
- // JSONObject jsonObject=new JSONObject();
- // jsonObject.optJSONObject(strResult);
- // System.out.println("Jsons parse error 1");
- // JSONArray jsonObjs =jsonObject.getJSONArray("messages");
- JSONTokener jsonParser = new JSONTokener(strResult);
- JSONObject jsonObject = (JSONObject) jsonParser.nextValue();
- JSONArray jsonObjs =jsonObject.getJSONArray("messages");
- for(int i = 0; i < jsonObjs.length() ; i++){
- JSONObject jsonObj = ((JSONObject)jsonObjs.opt(i)) ;
- System.out.println("Jsons parse error 0"+i);
- String msg = jsonObj.getString("msg");
- sb+= "msg:::"+msg + "\n";
- System.out.println(sb);
- }
- tvJson.setText(sb);
- } catch (JSONException e) {
- System.out.println("Jsons parse error !!!!");
- e.printStackTrace();
- }
- }
- //获取json文本
- private String connServerForResult(String strUrl) {
- // HttpGet对象
- HttpGet httpRequest = new HttpGet(strUrl);
- String strResult = "";
- try {
- // HttpClient对象
- HttpClient httpClient = new DefaultHttpClient();
- // 获得HttpResponse对象
- HttpResponse httpResponse = httpClient.execute(httpRequest);
- if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- // 取得返回的数据
- strResult = EntityUtils.toString(httpResponse.getEntity());
- // str=new String(str.getBytes("8859_1"),"GB2312");
- //tvJson.setText();
- }
- } catch (ClientProtocolException e) {
- tvJson.setText("protocol error");
- e.printStackTrace();
- } catch (IOException e) {
- tvJson.setText("IO error");
- e.printStackTrace();
- }
- try {
- strResult=new String(strResult.getBytes("8859_1"),"GB2312");
- } catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return strResult;
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.activity_json, menu);
- return true;
- }
- }
一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换。JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为。 – Json.org
JSON Vs XML
1.JSON和XML的数据可读性基本相同
2.JSON和XML同样拥有丰富的解析手段3.JSON相对于XML来讲,数据的体积小4.JSON与JavaScript的交互更加方便5.JSON对数据的描述性比XML较差
6.JSON的速度要远远快于XML
android2.3提供的json解析类
android的json解析部分都在包org.json下,主要有以下几个类: JSONObject:可以看作是一个json对象,这是系统中有关JSON定义的基本单元,其包含一对儿(Key/Value)数值。它对外部(External: 应用toString()方法输出的数值)调用的响应体现为一个标准的字符串(例如:{"JSON": "Hello, World"},最外被大括号包裹,其中的Key和Value被冒号":"分隔)。其对于内部(Internal)行为的操作格式略微,例如:初始化一个JSONObject实例,引用内部的put()方法添加数值:new JSONObject().put("JSON", "Hello, World!"),在Key和Value之间是以逗号","分隔。 Value的类型包括:Boolean 、 JSONArray 、 JSONObject 、 Number 、 String 或者默认值 JSONObject.NULL object 。
JSONStringer:json文本构建类 ,根据官方的解释,这个类可以帮助快速和便捷的创建JSON text。其最大的优点在于可以减少由于 格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。
JSONArray: 它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如: [value1,value2,value3],大家可以亲自利用简短的代码更加直观的了解其格式)。这个类的内部同样具有查询行为, get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值。 同样这个类的value类型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。
JSONTokener:json解析类
JSONException:json中用到的异常
JSONObject, JSONArray来构建json文本
- package com.jun.json;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.util.EntityUtils;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import org.json.JSONTokener;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- import android.widget.TextView;
- public class JsonActivity extends Activity {
- TextView tvJson=null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_json);
- tvJson=(TextView) findViewById(R.id.showTxt);
- String str=connServerForResult("http://bcs.duapp.com/weimeipicture/initial.txt");
- tvJson.setText(str);
- //获得多个Singer
- parseJsonMulti(str);
- }
- //解析多个数据的Json
- private void parseJsonMulti(String strResult) {
- String sb ="";
- try {
- // JSONObject jsonObject=new JSONObject();
- // jsonObject.optJSONObject(strResult);
- // System.out.println("Jsons parse error 1");
- // JSONArray jsonObjs =jsonObject.getJSONArray("messages");
- JSONTokener jsonParser = new JSONTokener(strResult);
- JSONObject jsonObject = (JSONObject) jsonParser.nextValue();
- JSONArray jsonObjs =jsonObject.getJSONArray("messages");
- for(int i = 0; i < jsonObjs.length() ; i++){
- JSONObject jsonObj = ((JSONObject)jsonObjs.opt(i)) ;
- System.out.println("Jsons parse error 0"+i);
- int id = jsonObj.getInt("id");
- String name = jsonObj.getString("name");
- String gender = jsonObj.getString("gender");
- sb+= "ID号"+id + ", 姓名:" + name + ",性别:" + gender+ "\n" ;
- System.out.println(sb);
- }
- tvJson.setText(sb);
- } catch (JSONException e) {
- System.out.println("Jsons parse error !!!!");
- e.printStackTrace();
- }
- }
- //获取json文本
- private String connServerForResult(String strUrl) {
- // HttpGet对象
- HttpGet httpRequest = new HttpGet(strUrl);
- String strResult = "";
- try {
- // HttpClient对象
- HttpClient httpClient = new DefaultHttpClient();
- // 获得HttpResponse对象
- HttpResponse httpResponse = httpClient.execute(httpRequest);
- if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- // 取得返回的数据
- strResult = EntityUtils.toString(httpResponse.getEntity());
- // str=new String(str.getBytes("8859_1"),"GB2312");
- //tvJson.setText();
- }
- } catch (ClientProtocolException e) {
- tvJson.setText("protocol error");
- e.printStackTrace();
- } catch (IOException e) {
- tvJson.setText("IO error");
- e.printStackTrace();
- }
- try {
- strResult=new String(strResult.getBytes("8859_1"),"GB2312");
- } catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return strResult;
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.activity_json, menu);
- return true;
- }
- }
服务器上面的json数据:
{"messages":[
{"id":"02","name":"tom","gender":"男"},
{"id":"03","name":"jerry","gender":"男"},
{"id":"04","name":"jim","gender":"男"},
{"id":"05","name":"lily","gender":"女"}]}
一定要注意数据格式,稍有不对就会解析不出来!