Android中与JSON相关的应用

 

JSON的定义:

一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式
,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换。JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为。 – Json.org

JSON的结构:

Name/Value Pairs,类似所熟知的Keyed list、 Hash table、Disctionary和Associative array。在Android平台中同时存在另外一个类 “Bundle“,某种程度上具有相似的行为。org.json.JSONObject

Array,一组有序的数据列表。org.json.JSONArray

在Android中包含四个与JSON相关的类和一个Exceptions:

JSONArray

JSONObject

JSONStringer

JSONTokener

JSONException

JSONObject:

这是系统中有关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。

有两个不同的取值方法:

get(): 在确定数值存在的条件下使用,否则当无法检索到相关Key时,将会抛出一个Exception信息。

opt(): 这个方法相对比较灵活,当无法获取所指定数值时,将会返回一个默认数值,并不会抛出异常。

JSONArray:

它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如:[value1,value2,value3],大家可以亲自利用简短的代码更加直观的了解其格式)。这个类的内部同样具有查询行为,get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值。

同样这个类的value类型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

JSONStringer:

根据官方的解释,这个类可以帮助快速和便捷的创建JSONtext。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntaxrules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。

根据下边的实例来了解其它相关信息:

1.string myString = new JSONStringer().object()

2.                                    .key(“AR”).value(“www.Androidres.com!”)

3.                                    .endObject()

4.                                    .toString();

结果是一组标准格式的JSON text:{”AR”:”www.Androidres.com!”}

其中的.object()和.endObject()必须同时使用,是为了按照Object标准给数值添加边界。同样,针对数组也有一组标准的方法来生成边界.array()和.endArray()。

JSONTokener:

这个是系统为JSONObject和JSONArray构造器解析JSON source string的类,它可以从source string中提取数值信息。

JSONException:

是JSON.org类抛出的异常信息。

下面引用一个完整的应用实例
(来自:androidsnippets.org)

应用JSONObject存储Map类型数值:

01.public static JSONObject getJSON(Map map) {

02.    Iterator iter = map.entrySet().iterator();

03.    JSONObject holder = new JSONObject();

04.

05.    while (iter.hasNext()) {

06.        Map.Entry pairs = (Map.Entry) iter.next();

07.        String key = (String) pairs.getKey();

08.        Map m = (Map) pairs.getValue();

09.        JSONObject data = new JSONObject();

10.

11.        try {

12.            Iterator iter2 = m.entrySet().iterator();

13.            while (iter2.hasNext()) {

14.                Map.Entry pairs2 = (Map.Entry) iter2.next();

15.                data.put((String) pairs2.getKey(), (String) pairs2.getValue());

16.            }

17.            holder.put(key, data);

18.        } catch (JSONException e) {

19.            Log.e(“Transforming”, “There was an error packaging JSON”,e);

20.        }

21.    }

22.

23.    return holder;

24.}

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

json数据格式解析我自己分为两种;

一种是普通的,一种是带有数组形式的;


 

普通形式的:
服务器端返回的json数据格式如下:

{
"userbean":{"Uid":"100196","Showname":"\u75af\u72c2\u7684\u7334\u5b50","Avtar":null,"State":1}}

分析代码如下:

// TODO 状态处理 500 200 
                int res = 0
                res 
= httpClient.execute(httpPost).getStatusLine().getStatusCode(); 
                
if (res == 200) { 
                    
/* 
                     * 当返回码为200时,做处理 
                     * 得到服务器端返回json数据,并做处理 
                     * 
*/ 
                    HttpResponse httpResponse 
= httpClient.execute(httpPost); 
                    StringBuilder builder 
= new StringBuilder(); 
                    BufferedReader bufferedReader2 
= new BufferedReader( 
                            
new InputStreamReader(httpResponse.getEntity().getContent())); 
                    String str2 
= ""
                    
for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2 
                            .readLine()) { 
                        builder.append(s); 
                    } 
                    Log.i(
"cat"">>>>>>" + builder.toString());

JSONObject jsonObject 
= new JSONObject(builder.toString()) 
                        .getJSONObject(
"userbean"); 

                String Uid; 
                String Showname; 
                String Avtar; 
                String State; 

                Uid 
= jsonObject.getString("Uid"); 
                Showname 
= jsonObject.getString("Showname"); 
                Avtar 
= jsonObject.getString("Avtar"); 
                State 
= jsonObject.getString("State");
带数组形式的:
服务器端返回的数据格式为:

{
"calendar"
    {
"calendarlist"
            [ 
            {
"calendar_id":"1705","title":"(\u4eb2\u5b50)ddssd","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288927800","endshowtime":"1288931400","allDay":false}, 
            {
"calendar_id":"1706","title":"(\u65c5\u884c)","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288933200","endshowtime":"1288936800","allDay":false
            ] 
    } 
}

分析代码如下:

// TODO 状态处理 500 200 
                int res = 0
                res 
= httpClient.execute(httpPost).getStatusLine().getStatusCode(); 
                
if (res == 200) { 
                    
/* 
                     * 当返回码为200时,做处理 
                     * 得到服务器端返回json数据,并做处理 
                     * 
*/ 
                    HttpResponse httpResponse 
= httpClient.execute(httpPost); 
                    StringBuilder builder 
= new StringBuilder(); 
                    BufferedReader bufferedReader2 
= new BufferedReader( 
                            
new InputStreamReader(httpResponse.getEntity().getContent())); 
                    String str2 
= ""
                    
for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2 
                            .readLine()) { 
                        builder.append(s); 
                    } 
                    Log.i(
"cat"">>>>>>" + builder.toString()); 
                    
/** 
                     * 这里需要分析服务器回传的json格式数据, 
                     
*/ 
                    JSONObject jsonObject 
= new JSONObject(builder.toString()) 
                            .getJSONObject(
"calendar"); 
                    JSONArray jsonArray 
= jsonObject.getJSONArray("calendarlist"); 
                    
for(int i=0;i<jsonArray.length();i++){ 
                        JSONObject jsonObject2 
= (JSONObject)jsonArray.opt(i); 
                        CalendarInfo calendarInfo 
= new CalendarInfo(); 
                        calendarInfo.setCalendar_id(jsonObject2.getString(
"calendar_id")); 
                        calendarInfo.setTitle(jsonObject2.getString(
"title")); 
                        calendarInfo.setCategory_name(jsonObject2.getString(
"category_name")); 
                        calendarInfo.setShowtime(jsonObject2.getString(
"showtime")); 
                        calendarInfo.setEndtime(jsonObject2.getString(
"endshowtime")); 
                        calendarInfo.setAllDay(jsonObject2.getBoolean(
"allDay")); 
                        calendarInfos.add(calendarInfo); 
                    }

总结,普通形式的只需用JSONObject ,带数组形式的需要使用JSONArray 将其变成一个list。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值