JSON的定義:
原文地址:
http://www.open-open.com/lib/view/open1326376799874.html
一種輕量級(jí)的數(shù)據(jù)交換格式,具有良好的可讀和便于快速編寫的特性。業(yè)內(nèi)主流技術(shù)為其提供了完整的解決方案(有點(diǎn)類似于正則表達(dá)式 ,獲得了當(dāng)今大部分語言的支持),從而可以在不同平臺(tái)間進(jìn)行數(shù)據(jù)交換。JSON采用兼容性很高的文本格式,同時(shí)也具備類似于C語言體系的行為。 – Json.org
JSON Vs XML
1.JSON和XML的數(shù)據(jù)可讀性基本相同
2.JSON和XML同樣擁有豐富的解析手段
3.JSON相對(duì)于XML來講,數(shù)據(jù)的體積小
4.JSON與JavaScript的交互更加方便
5.JSON對(duì)數(shù)據(jù)的描述性比XML較差
6.JSON的速度要遠(yuǎn)遠(yuǎn)快于XML
android2.3提供的json解析類
android的json解析部分都在包org.json下,主要有以下幾個(gè)類:
JSONObject:可以看作是一個(gè)json對(duì)象,這是系統(tǒng)中有關(guān)JSON定義的基本單元,其包含一對(duì)兒(Key/Value)數(shù)值。它對(duì)外部(External: 應(yīng)用toString()方法輸出的數(shù)值)調(diào)用的響應(yīng)體現(xiàn)為一個(gè)標(biāo)準(zhǔn)的字符串(例如:{"JSON": "Hello, World"},最外被大括號(hào)包裹,其中的Key和Value被冒號(hào)":"分隔)。其對(duì)于內(nèi)部(Internal)行為的操作格式略微,例如:初始化一個(gè)JSONObject實(shí)例,引用內(nèi)部的put()方法添加數(shù)值:new JSONObject().put("JSON", "Hello, World!"),在Key和Value之間是以逗號(hào)","分隔。Value的類型包括:Boolean、JSONArray、JSONObject、Number、String或者默認(rèn)值JSONObject.NULL object 。
JSONStringer:json文本構(gòu)建類 ,根據(jù)官方的解釋,這個(gè)類可以幫助快速和便捷的創(chuàng)建JSON text。其最大的優(yōu)點(diǎn)在于可以減少由于 格式的錯(cuò)誤導(dǎo)致程序異常,引用這個(gè)類可以自動(dòng)嚴(yán)格按照J(rèn)SON語法規(guī)則(syntax rules)創(chuàng)建JSON text。每個(gè)JSONStringer實(shí)體只能對(duì)應(yīng)創(chuàng)建一個(gè)JSON text。。其最大的優(yōu)點(diǎn)在于可以減少由于格式的錯(cuò)誤導(dǎo)致程序異常,引用這個(gè)類可以自動(dòng)嚴(yán)格按照J(rèn)SON語法規(guī)則(syntax rules)創(chuàng)建JSON text。每個(gè)JSONStringer實(shí)體只能對(duì)應(yīng)創(chuàng)建一個(gè)JSON text。
JSONArray:它代表一組有序的數(shù)值。將其轉(zhuǎn)換為String輸出(toString)所表現(xiàn)的形式是用方括號(hào)包裹,數(shù)值以逗號(hào)”,”分隔(例如: [value1,value2,value3],大家可以親自利用簡(jiǎn)短的代碼更加直觀的了解其格式)。這個(gè)類的內(nèi)部同樣具有查詢行為, get()和opt()兩種方法都可以通過index索引返回指定的數(shù)值,put()方法用來添加或者替換數(shù)值。同樣這個(gè)類的value類型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默認(rèn)值JSONObject.NULL object。
JSONTokener:json解析類
JSONException:json中用到的異常
JSONObject, JSONArray來構(gòu)建json文本
-
-
-
-
-
-
-
-
-
- try {
-
- JSONObject person = new JSONObject();
-
- JSONArray phone = new JSONArray();
- phone.put("12345678").put("87654321");
- person.put("phone", phone);
-
- person.put("name", "yuanzhifei89");
- person.put("age", 100);
-
- JSONObject address = new JSONObject();
- address.put("country", "china");
- address.put("province", "jiangsu");
- person.put("address", address);
- person.put("married", false);
- } catch (JSONException ex) {
-
- throw new RuntimeException(ex);
- }
getType和optType api的使用
getType可以將要獲取的鍵的值轉(zhuǎn)換為指定的類型,如果無法轉(zhuǎn)換或沒有值則拋出JSONException
optType也是將要獲取的鍵的值轉(zhuǎn)換為指定的類型,無法轉(zhuǎn)換或沒有值時(shí)返回用戶提供或這默認(rèn)提供的值
- try {
-
-
- phone.getLong(0);
- person.getLong("name");
- phone.optLong(0);
- phone.optLong(0, 1000);
- person.optLong("name");
- person.optLong("name", 1000);
- } catch (JSONException ex) {
-
- }
除了上面的兩個(gè)類,還可以使用JSONStringer來構(gòu)建json文本
- try {
- JSONStringer jsonText = new JSONStringer();
-
- jsonText.object();
-
- jsonText.key("phone");
-
- jsonText.array();
- jsonText.value("12345678").value("87654321");
- jsonText.endArray();
-
- jsonText.key("name");
- jsonText.value("yuanzhifei89");
- jsonText.key("age");
- jsonText.value(100);
-
- jsonText.key("address");
-
- jsonText.object();
- jsonText.key("country");
- jsonText.value("china");
- jsonText.key("province");
- jsonText.value("jiangsu");
- jsonText.endObject();
-
- jsonText.key("married");
- jsonText.value(false);
-
-
- jsonText.endObject();
- } catch (JSONException ex) {
- throw new RuntimeException(ex);
- }
json文本解析類JSONTokener
按照RFC4627規(guī)范將json文本解析為相應(yīng)的對(duì)象。
對(duì)于將json文本解析為對(duì)象,只需要用到該類的兩個(gè)api:
構(gòu)造函數(shù)
public Object nextValue();
-
-
-
-
-
-
-
-
- private static final String JSON =
- "{" +
- " \"phone\" : [\"12345678\", \"87654321\"]," +
- " \"name\" : \"yuanzhifei89\"," +
- " \"age\" : 100," +
- " \"address\" : { \"country\" : \"china\", \"province\" : \"jiangsu\" }," +
- " \"married\" : false," +
- "}";
-
- try {
- JSONTokener jsonParser = new JSONTokener(JSON);
-
-
- JSONObject person = (JSONObject) jsonParser.nextValue();
-
- person.getJSONArray("phone");
- person.getString("name");
- person.getInt("age");
- person.getJSONObject("address");
- person.getBoolean("married");
- } catch (JSONException ex) {
-
- }
其它的api基本就是用來查看json文本中的文本的
- try {
- JSONTokener jsonParser = new JSONTokener(JSON);
-
- jsonParser.next(8);
-
-
- jsonParser.next();
-
-
- jsonParser.nextClean();
-
-
- jsonParser.nextString('a');
-
-
- jsonParser.nextTo("0089");
-
-
- jsonParser.back();
- jsonParser.next();
-
-
- jsonParser.skipPast("address");
- jsonParser.next(8);
-
-
- jsonParser.skipTo('m');
- jsonParser.next(8);
- } catch (JSONException ex) {
-
- }
以下是一個(gè)標(biāo)準(zhǔn)的JSON請(qǐng)求實(shí)現(xiàn)過程:
01 |
HttpPost request = new HttpPost(url); |
03 |
JSONObject param = new JSONObject(); |
04 |
param.put( "name" , "rarnu" ); |
05 |
param.put( "password" , "123456" ); |
07 |
StringEntity se = new StringEntity(param.toString()); |
08 |
request.setEntity(se); |
10 |
HttpResponse httpResponse = new DefaultHttpClient().execute(request); |
12 |
String retSrc = EntityUtils.toString(httpResponse.getEntity()); |
14 |
JSONObject result = new JSONObject( retSrc); |
15 |
String token = result.get( "token" ); |
下面這個(gè)是自己修改別人的小例子,主要是加一些注釋和講解,這個(gè)例子主要是使用android進(jìn)行json解析。
1 |
單數(shù)據(jù){'singer':{'id':01,'name':'tom','gender':'男'}} |
2 |
多個(gè)數(shù)據(jù){"singers":[ |
3 |
{'id':02,'name':'tom','gender':'男'}, |
4 |
{'id':03,'name':'jerry,'gender':'男'}, |
5 |
{'id':04,'name':'jim,'gender':'男'}, |
6 |
{'id':05,'name':'lily,'gender':'女'}]} |
下面的類主要是解析單個(gè)數(shù)據(jù)parseJson()和多個(gè)數(shù)據(jù)的方法parseJsonMulti():
01 |
public class JsonActivity extends Activity { |
02 |
/** Called when the activity is first created. */ |
03 |
private TextView tvJson; |
04 |
private Button btnJson; |
05 |
private Button btnJsonMulti; |
07 |
public void onCreate(Bundle savedInstanceState) { |
08 |
super .onCreate(savedInstanceState); |
09 |
setContentView(R.layout.main); |
10 |
tvJson = (TextView) this .findViewById(R.id.tvJson); |
11 |
btnJson = (Button) this .findViewById(R.id.btnJson); |
12 |
btnJsonMulti = (Button) this .findViewById(R.id.btnJsonMulti); |
13 |
btnJson.setOnClickListener( new View.OnClickListener() { |
15 |
public void onClick(View v) { |
18 |
String strUrl = ServerPageUtil.getStrUrl(UrlsOfServer.JSON_SINGER); |
20 |
String strResult = connServerForResult(strUrl); |
25 |
btnJsonMulti.setOnClickListener( new View.OnClickListener() { |
27 |
public void onClick(View v) { |
28 |
String strUrl = ServerPageUtil.getStrUrl(UrlsOfServer.JSON_SINGERS); |
29 |
String strResult = connServerForResult(strUrl); |
31 |
parseJsonMulti(strResult); |
35 |
private String connServerForResult(String strUrl) { |
37 |
HttpGet httpRequest = new HttpGet(strUrl); |
38 |
String strResult = "" ; |
41 |
HttpClient httpClient = new DefaultHttpClient(); |
43 |
HttpResponse httpResponse = httpClient.execute(httpRequest); |
44 |
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { |
46 |
strResult = EntityUtils.toString(httpResponse.getEntity()); |
48 |
} catch (ClientProtocolException e) { |
49 |
tvJson.setText( "protocol error" ); |
51 |
} catch (IOException e) { |
52 |
tvJson.setText( "IO error" ); |
58 |
private void parseJson(String strResult) { |
60 |
JSONObject jsonObj = new JSONObject(strResult).getJSONObject( "singer" ); |
61 |
int id = jsonObj.getInt( "id" ); |
62 |
String name = jsonObj.getString( "name" ); |
63 |
String gender = jsonObj.getString( "gender" ); |
64 |
tvJson.setText( "ID號(hào)" +id + ", 姓名:" + name + ",性別:" + gender); |
65 |
} catch (JSONException e) { |
66 |
System.out.println( "Json parse error" ); |
71 |
private void parseJsonMulti(String strResult) { |
73 |
JSONArray jsonObjs = new JSONObject(strResult).getJSONArray( "singers" ); |
75 |
for ( int i = 0 ; i < jsonObjs.length() ; i++){ |
76 |
JSONObject jsonObj = ((JSONObject)jsonObjs.opt(i)) |
77 |
.getJSONObject( "singer" ); |
78 |
int id = jsonObj.getInt( "id" ); |
79 |
String name = jsonObj.getString( "name" ); |
80 |
String gender = jsonObj.getString( "gender" ); |
81 |
s += "ID號(hào)" +id + ", 姓名:" + name + ",性別:" + gender+ "\n" ; |
84 |
} catch (JSONException e) { |
85 |
System.out.println( "Jsons parse error !" ); |
posted on 2013-05-09 19:27
Terry Zou 閱讀(354)
評(píng)論(1) 編輯 收藏 所屬分類:
Android