JSON的定義:
一種輕量級的數據交換格式,具有良好的可讀和便於快速編寫的特性。業內主流技術爲其提供了完整的解決方案(有點類似於正則表達式 ,獲得了當今大部分語言的支持),從而可以在不同平臺間進行數據交換。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文本
-
-
-
-
-
-
-
-
-
-
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可以將要獲取的鍵的值轉換爲指定的類型,如果無法轉換或沒有值則拋出JSONException
optType也是將要獲取的鍵的值轉換爲指定的類型,無法轉換或沒有值時返回用戶提供或這默認提供的值
-
try {
-
-
-
phone.getLong(0);
-
person.getLong("name");
-
phone.optLong(0);
-
phone.optLong(0, 1000);
-
person.optLong("name");
-
person.optLong("name", 1000);
-
} catch (JSONException ex) {
-
-
}
除了上面的兩個類,還可以使用JSONStringer來構建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規範將json文本解析爲相應的對象。
對於將json文本解析爲對象,只需要用到該類的兩個api:
構造函數
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) {
-
-
}
以下是一個標準的JSON請求實現過程:
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" ); |
下面這個是自己修改別人的小例子,主要是加一些註釋和講解,這個例子主要是使用android進行json解析。
1 |
單數據{'singer':{'id':01,'name':'tom','gender':'男'}} |
3 |
{'id':02,'name':'tom','gender':'男'}, |
4 |
{'id':03,'name':'jerry,'gender':'男'}, |
5 |
{'id':04,'name':'jim,'gender':'男'}, |
6 |
{'id':05,'name':'lily,'gender':'女'}]} |
下面的類主要是解析單個數據parseJson()和多個數據的方法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號" +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號" +id
+ ",
姓名:" +
name + ",性別:" +
gender+ "\n" ; |
84 |
} catch (JSONException
e) { |
85 |
System.out.println( "Jsons
parse error !" ); |