Chinaunix首页 | 论坛 | 博客
  • 博客访问: 77217
  • 博文数量: 8
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 599
  • 用 户 组: 普通用户
  • 注册时间: 2013-06-27 16:46
个人简介

哎……马上就要毕业了!求工作啊^0^

文章分类

全部博文(8)

文章存档

2013年(8)

我的朋友

分类: Android平台

2013-08-25 21:30:10

1.Json的定义:JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript的一个子集.JSON采用完全独立于语言的文本格式,                           但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交                             换语言。易于人阅读和编写,同时也易于机器解析和生成。

2.Json的结构:

             ●对象是一组无序的键值对集合

                1.一个对象以“{”(左括号)开始,“}”(右括号)结束。
                 2.每个“名称”后跟一个“:”(冒号)。
                 3.“‘名称/值’ 对”之间使用“,”(逗号)分隔。
               列如:{"name":"Scoield","age":22} 

              ●数组是值(value)的有序集合

                1.一个数组以“[”(左中括号)开始,“]”(右中括号)结束。
                2.值之间使用“,”(逗号)分隔。
                列如:[{"name":"Scoield","age":22},{"name":"Scoield1","age":23}]

             ●值(value)可以是双引号括起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array)。这些结  构可以嵌套。

             ●字符串(string)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。 字符串(string)与C或者Java的字符串非常相似。

             ●数值(number)也与C或者Java的数值非常相似。除去未曾使用的八进制与十六进制格式。除去一些编码细节。

3.在Android中包含4个JSON相关的类(JSONArray,JSONObject,JSONStringer,JSONTokener)和一个异常类(JSONException)

              ●JSONObject:JSON定义的几本单元,里面是键值对形式;

                  {} 每一个大括号里面的内容 就是一个json对象 ------- JSONObject;一个json对象调用tostring方法将输出一个标准的字符串,列如:                                         {"name":"scoield"};也可以像map一样调用put方法添加值:new JSONObject.put("name","Scoield");
                 有两种不同的取值方式:
                 get():在确定存在的条件下使用,如果没有相关的key会抛异常
                 opt():相对于get()取值较灵活,在无法获取相关数值的情况下不会抛出异常,会返回默认值;

              ●JSONArray:代表一组有序的数值;

                 [] 代表一个json的数组,数组里面可以有多个{} ------- JSONArray,用tostring方法输出结果为外面用方括号包裹的字符串;他同样具有和JSONObject                  一样的get(),opt()和put()方法;

              ●JSONStringer:可以快速便捷的创建JSON text;

                 使用这个类优点在于可以减少由于格式的错误而导致程序异常,但是每个JSONStringer对象只能创建一个JSONtext;
                

点击(此处)折叠或打开

  1. String json =new JSONStringer().object().key("name").value("Scoield").endObject().toString();
                 这句可创建一个{”name“:"Scoield"};

            ●JSONTokener:是为JSONObject和JSONArray构造器解析JSON source string 的类,可以从source string中提取数值

               文档中的案列:
              

点击(此处)折叠或打开

  1. String json = "{"
  2.                  + " \"query\": \"Pizza\", "
  3.                  + " \"locations\": [ 94043, 90210 ] "
  4.                  + "}";

  5.                  JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
  6.                  System.out.println(object.toString());//打印{"locations":[94043,90210],"query":"Pizza"}
  7.                  String query = object.getString("query");
  8.                  System.out.println("query:"+query);//打印query:Pizza
  9.                  JSONArray locations = object.getJSONArray("locations");
  10.                  System.out.println("locations:"+locations);//打印locations:[94043,90210]

             ●JSONException:是JSON.org类抛出的异常信息→如果JSONObject中存取的不是键值对形式的数据会抛出此异常

◎小案例^0^

    1.首先获得json数据源,懒得自己创建服务器,就用了豆瓣的api,地址:,这个得到的是一个xml文档,在地址后面加上参数"?alt=json",即可得到该文档的json数据;由于数据较多……下面只获取部分

      

点击(此处)折叠或打开

  1. {
  2.   "category":
  3.      {
  4.      "@scheme":"http:\/\/\/2007#kind",
  5.      "@term":"http:\/\/\/2007#book"
  6.      },
  7.   "db:tag":
  8.     [
  9.      {"@count":3182,"@name":"算法"},
  10.      {"@count":1798,"@name":"算法导论"},
  11.      {"@count":1368,"@name":"计算机"},
  12.      {"@count":1046,"@name":"编程"},
  13.      {"@count":790,"@name":"经典"},
  14.      {"@count":717,"@name":"algorithm"},
  15.      {"@count":558,"@name":"计算机科学"},
  16.      {"@count":443,"@name":"程序设计"}
  17.     ],
  18.   "title":
  19.      {"$t":"算法导论"},
  20.   "author":
  21.      [{"name":{"$t":"[美] Thomas H.Cormen"}},{"name":{"$t":"Charles E.Leiserson"}},
  22.      {"name":{"$t":"Ronald L.Rivest"}},{"name":{"$t":"Clifford Stein"}}],
  23.   "summary":
  24.      {"$t":"这本书深入浅出,全面地介绍了计算机算法。对每一个算法的分析既易于理解又十分有趣,并保持了数学严谨性。本书的设计目标全面,适用于多种用途。涵盖的内容有:算法在计算中的作用,概率分析和随机算法的介绍。书中专门讨论了线性规划,介绍了动态规划的两个应用,随机化和线性规划技术的近似算法等,还有有关递归求解、快速排序中用到的划分方法与期望线性时间顺序统计算法,以及对贪心算法元素的讨论。此书还介绍了对强连通子图算法正确性的证明,对哈密顿回路和子集求和问题的NP完全性的证明等内容。全书提供了900多个练习题和思考题以及叙述较为详细的实例研究。"},
  25.   "link":
  26.      [
  27.      {"@rel":"self","@href":"http:\/\/api.douban.com\/book\/subject\/1885170"},
  28.      {"@rel":"alternate","@href":"http:\/\/book.douban.com\/subject\/1885170\/"},
  29.      {"@rel":"image","@href":"http:\/\/img3.douban.com\/spic\/s1959967.jpg"},
  30.      {"@rel":"mobile","@href":"http:\/\/m.douban.com\/book\/subject\/1885170\/"}
  31.      ],
  32.   "db:attribute":
  33.      [
  34.      {"$t":"7111187776","@name":"isbn10"},
  35.      {"$t":"9787111187776","@name":"isbn13"},
  36.      {"$t":"Thomas H.Cormen\n达特茅斯学院计算机科学系副教授\nCharles E.Leiserson\n麻省理工学院计算机科学与电气工程系教授\nRonald L.Rivest\n麻省理工学院计算机科学系 Andrew与Erna Viterbi具名教授\nClifford Stein\n哥伦比亚大学工业工程与运筹学副教授","@name":"author-intro"},
  37.      {"$t":"754","@name":"pages"},
  38.      {"$t":"潘金贵 等","@name":"translator"},
  39.      {"$t":"[美] Thomas H.Cormen","@name":"author"},
  40.      {"$t":"Charles E.Leiserson","@name":"author"},
  41.      {"$t":"Ronald L.Rivest","@name":"author"},
  42.      {"$t":"Clifford Stein","@name":"author"},
  43.      {"$t":"85.00元","@name":"price"},
  44.      {"$t":"机械工业出版社","@name":"publisher"},
  45.      {"$t":"平装","@name":"binding"},
  46.      {"$t":"2006-9","@name":"pubdate"},
  47.      {"$t":"Introduction to Algorithms","@name":"aka"},
  48.      {"$t":"算法导论","@name":"title"}
  49.     ],
  50.  "id":
  51.        {"$t":"http:\/\/api.douban.com\/book\/subject\/1885170"},
  52.  "gd:rating":{"@min":0,"@numRaters":3725,"@average":"9.4","@max":10}
  53. }

      2.创建Android项目,编写布局文件main.xml:用tablerow布局方便显示

       

点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <FrameLayout xmlns:android=""
  3.     android:layout_width="match_parent"
  4.     android:layout_height="match_parent" >
  5.     <TableLayout
  6.         android:layout_width="match_parent"
  7.         android:layout_height="match_parent" >
  8.         <TableRow
  9.             android:layout_width="match_parent"
  10.             android:layout_height="wrap_content" >
  11.             <TextView
  12.                 android:layout_width="wrap_content"
  13.                 android:layout_height="wrap_content"
  14.                 android:text="标题" />
  15.             <TextView
  16.                 android:id="@+id/tv_title"
  17.                 android:layout_width="wrap_content"
  18.                 android:layout_height="wrap_content" />
  19.         </TableRow>
  20.         <TableRow
  21.             android:layout_width="match_parent"
  22.             android:layout_height="wrap_content" >

  23.             <TextView
  24.                 android:layout_width="wrap_content"
  25.                 android:layout_height="wrap_content"
  26.                 android:text="标签 :" />

  27.             <TextView
  28.                 android:id="@+id/tv_tag"
  29.                 android:layout_width="wrap_content"
  30.                 android:layout_height="wrap_content" />
  31.         </TableRow>
  32.         <TableRow
  33.             android:layout_width="match_parent"
  34.             android:layout_height="wrap_content" >

  35.             <TextView
  36.                 android:layout_width="wrap_content"
  37.                 android:layout_height="wrap_content"
  38.                 android:text="作者" />

  39.             <TextView
  40.                 android:id="@+id/tv_author"
  41.                 android:layout_width="wrap_content"
  42.                 android:layout_height="wrap_content" />
  43.         </TableRow>

  44.         <TableRow
  45.             android:layout_width="match_parent"
  46.             android:layout_height="wrap_content" >

  47.             <TextView
  48.                 android:layout_width="wrap_content"
  49.                 android:layout_height="wrap_content"
  50.                 android:text="页数" />

  51.             <TextView
  52.                 android:id="@+id/tv_pages"
  53.                 android:layout_width="wrap_content"
  54.                 android:layout_height="wrap_content" />
  55.         </TableRow>
  56.         <TableRow
  57.             android:layout_width="match_parent"
  58.             android:layout_height="wrap_content" >

  59.             <TextView
  60.                 android:layout_width="wrap_content"
  61.                 android:layout_height="wrap_content"
  62.                 android:text="价格" />

  63.             <TextView
  64.                 android:id="@+id/tv_price"
  65.                 android:layout_width="wrap_content"
  66.                 android:layout_height="wrap_content" />
  67.         </TableRow>
  68.         <TableRow
  69.             android:layout_width="match_parent"
  70.             android:layout_height="wrap_content" >

  71.             <TextView
  72.                 android:layout_width="wrap_content"
  73.                 android:layout_height="wrap_content"
  74.                 android:text="简介" />

  75.             <TextView
  76.                 android:id="@+id/tv_summary"
  77.                 android:layout_width="wrap_content"
  78.                 android:layout_height="wrap_content" />
  79.         </TableRow>
  80.     </TableLayout>

  81.     <LinearLayout
  82.         android:id="@+id/ll_book_detail"
  83.         android:layout_width="match_parent"
  84.         android:layout_height="match_parent"
  85.         android:background="@android:color/background_dark"
  86.         android:gravity="center"
  87.         android:visibility="invisible"
  88.          >
  89.         <ProgressBar
  90.             android:layout_width="wrap_content"
  91.             android:layout_height="wrap_content" />
  92.     </LinearLayout>
  93. </FrameLayout>
       3.编写activity文件;

          

点击(此处)折叠或打开

  1. public class JsonProjectActovoty extends Activity {
  2.     /** Called when the activity is first created. */
  3.     //定义相关控件
  4.     TextView tv_title,tv_tag,tv_pages;
  5.     TextView tv_summary,tv_author,tv_price;
  6.     LinearLayout ll_layout;
  7.     @Override
  8.     public void onCreate(Bundle savedInstanceState) {
  9.         super.onCreate(savedInstanceState);
  10.         setContentView(R.layout.book_detail);
  11.         //初始化相关控件
  12.         tv_title= (TextView)this.findViewById(R.id.tv_title);
  13.         tv_summary = (TextView)this.findViewById(R.id.tv_summary);
  14.         tv_author = (TextView)this.findViewById(R.id.tv_author);
  15.         tv_tag=(TextView)this.findViewById(R.id.tv_tag);
  16.         tv_pages = (TextView)this.findViewById(R.id.tv_pages);
  17.         tv_price = (TextView)this.findViewById(R.id.tv_price);
  18.         ll_layout = (LinearLayout)this.findViewById(R.id.ll_book_detail);
  19.         //代码量较多,则编写在另一个方法中
  20.         getJsonData();
  21.     }
  22.     
  23.     private void getJsonData() {
  24.         //网络下载数据相对耗时,使用异步加载,减少主线程负担
  25.         new AsyncTask<String, Void, Boolean>() {
  26.             String title;
  27.             String summary ;
  28.             String tag;
  29.             String author,pages,price;
  30.             @Override
  31.             protected void onPreExecute() {
  32.                 // TODO Auto-generated method stub
  33.                 //显示进度条
  34.                 ll_layout.setVisibility(View.VISIBLE);
  35.                 super.onPreExecute();
  36.             }

  37.             @Override
  38.             protected void onPostExecute(Boolean result) {
  39.                 // TODO Auto-generated method stub
  40.                 //设置进度条消失
  41.                 ll_layout.setVisibility(View.INVISIBLE);
  42.                 //如果获取到数据则把数据显示到屏幕
  43.                 if (result) {
  44.                     tv_title.setText(title);
  45.                     tv_summary.setText(summary);
  46.                     tv_tag.setText(tag);
  47.                     tv_author.setText(author);
  48.                     tv_pages.setText(pages);
  49.                     tv_price.setText(price);
  50.                 }else {
  51.                     Toast.makeText(getApplicationContext(),"获取数据失败",0).show();
  52.                 }
  53.                 super.onPostExecute(result);
  54.             }

  55.             @Override
  56.             protected Boolean doInBackground(String... params) {
  57.                 // TODO Auto-generated method stub
  58.                 String path = "?alt=json";
  59.                 try {
  60.                     URL url = new URL(path);
  61.                     Source source = new Source(url.openConnection());//这个需加入jericho-html-3.1.jar包
  62.                  String jsonstr = source.toString();
  63.                  //得到一个JSONObject对象
  64.                  JSONObject jsonObj = new JSONObject(jsonstr);
  65.                  //获取title
  66.                  String titlestr = jsonObj.get("title").toString();
  67.                  JSONObject jsontitle = new JSONObject(titlestr);
  68.                  title = jsontitle.getString("$t");
  69.                 
  70.                  //获取标签
  71.                  String tagstr = jsonObj.getString("db:tag");
  72.                  JSONArray jsonArray = new JSONArray(tagstr);
  73.                  StringBuffer sb = new StringBuffer();
  74.                  String tagarr = null;
  75.                  for (int i = 0; i < jsonArray.length(); i++) {
  76.                         tagarr = jsonArray.getString(i);
  77.                         JSONObject jsonObject = new JSONObject(tagarr);
  78.                         tag = jsonObject.getString("@name");
  79.                         sb.append(tag+"/");
  80.                     }
  81.                  tag =sb.substring(0, sb.length()-1);
  82.                 
  83.                  //获取作者
  84.                  String authorstr = jsonObj.getString("author");
  85.                  JSONArray authorArray = new JSONArray(authorstr);
  86.                  StringBuffer sbauthor = new StringBuffer();
  87.                  String authorarr = null;
  88.                  for (int i = 0; i < authorArray.length(); i++) {
  89.                      System.out.println(authorArray.length());
  90.                      authorarr = authorArray.getString(i);
  91.                         JSONObject jsonObject = new JSONObject(authorarr);
  92.                         String authorName = jsonObject.getString("name");
  93.                         jsonObject = new JSONObject(authorName);
  94.                         author = jsonObject.getString("$t");
  95.                         sbauthor.append(author+"/");
  96.                     }
  97.                  author =sbauthor.substring(0, sbauthor.length()-1);
  98.                 
  99.                  //获取价格与页数
  100.                  String str = jsonObj.getString("db:attribute");
  101.                  JSONArray array = new JSONArray(str);
  102.                  sb = new StringBuffer();
  103.                  String bookinfo = null;
  104.                  for (int i = 0; i < array.length(); i++) {
  105.                      bookinfo = array.getString(i);
  106.                      JSONObject jsonObject = new JSONObject(bookinfo);
  107.                         if ("price".equals(jsonObject.getString("@name"))) {
  108.                             price = jsonObject.getString("$t");
  109.                         }
  110.                         if ("pages".equals(jsonObject.getString("@name"))) {
  111.                             pages = jsonObject.getString("$t");
  112.                         }
  113.                     }
  114.                  //获取简介
  115.                  String summarystr = jsonObj.getString("summary");
  116.                  JSONObject jsonsummary = new JSONObject(summarystr);
  117.                  summary = jsonsummary.getString("$t");
  118.                  return true;
  119.                 } catch (Exception e) {
  120.                     Toast.makeText(getApplicationContext(), "获取数据失败", 0).show();
  121.                     return false;
  122.                 }
  123.             }
  124.         }.execute();
  125.     }
  126. }

    3.最后不要忘了加入访问网络的权限;运行程序可看到


阅读(6035) | 评论(3) | 转发(1) |
给主人留下些什么吧!~~

scoield2014-04-28 14:12:09

whatlailai:搞定了,Json数据的问题。

我都很久没上博客了…最近忙毕业论文……

回复 | 举报

whatlailai2014-03-20 08:51:04

whatlailai:你好,我按照你的Demo试了可以运行,但是我把豆瓣的JSON改成自己的之后总是抓不完整:

Source source = new Source(url.openConnection());//这个需加入jericho-html-3.1.jar包
String jsonstr = source.toString();
Log.i("抓取","内容"+jsonstr);

这里的LOG总是显示不完整,不知道是因为字节太多还是什么原因,求教,谢谢!

搞定了,Json数据的问题。

回复 | 举报

whatlailai2014-03-19 16:51:05

你好,我按照你的Demo试了可以运行,但是我把豆瓣的JSON改成自己的之后总是抓不完整:

Source source = new Source(url.openConnection());//这个需加入jericho-html-3.1.jar包
String jsonstr = source.toString();
Log.i("抓取","内容"+jsonstr);

这里的LOG总是显示不完整,不知道是因为字节太多还是什么原因,求教,谢谢!