Json方式获取网络数据
来源:互联网 发布:sql培训班昆山 编辑:程序博客网 时间:2024/06/01 09:58
原文http://blog.chinaunix.net/uid-29006784-id-3865030.html
1.Json的定义:JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript的一个子集.JSON采用完全独立于语言的文本格式, 但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交 换语言。易于人阅读和编写,同时也易于机器解析和生成。
2.Json的结构:
●对象是一组无序的键值对集合
1.一个对象以“{”(左括号)开始,“}”(右括号)结束。
2.每个“名称”后跟一个“:”(冒号)。
3.“‘名称/值’ 对”之间使用“,”(逗号)分隔。
2.每个“名称”后跟一个“:”(冒号)。
3.“‘名称/值’ 对”之间使用“,”(逗号)分隔。
列如:{"name":"Scoield","age":22}
●数组是值(value)的有序集合
1.一个数组以“[”(左中括号)开始,“]”(右中括号)结束。
2.值之间使用“,”(逗号)分隔。
列如:[{"name":"Scoield","age":22},{"name":"Scoield1","age":23}]
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()取值较灵活,在无法获取相关数值的情况下不会抛出异常,会返回默认值;
有两种不同的取值方式:
get():在确定存在的条件下使用,如果没有相关的key会抛异常
opt():相对于get()取值较灵活,在无法获取相关数值的情况下不会抛出异常,会返回默认值;
●JSONArray:代表一组有序的数值;
[] 代表一个json的数组,数组里面可以有多个{} ------- JSONArray,用tostring方法输出结果为外面用方括号包裹的字符串;他同样具有和JSONObject 一样的get(),opt()和put()方法;
●JSONStringer:可以快速便捷的创建JSON text;
使用这个类优点在于可以减少由于格式的错误而导致程序异常,但是每个JSONStringer对象只能创建一个JSONtext;
这句可创建一个{”name“:"Scoield"};
点击(此处)折叠或打开
- String json =new JSONStringer().object().key("name").value("Scoield").endObject().toString();
●JSONTokener:是为JSONObject和JSONArray构造器解析JSON source string 的类,可以从source string中提取数值
文档中的案列:
点击(此处)折叠或打开
- String json = "{"
- + " \"query\": \"Pizza\", "
- + " \"locations\": [ 94043, 90210 ] "
- + "}";
- JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
- System.out.println(object.toString());//打印{"locations":[94043,90210],"query":"Pizza"}
- String query = object.getString("query");
- System.out.println("query:"+query);//打印query:Pizza
- JSONArray locations = object.getJSONArray("locations");
- System.out.println("locations:"+locations);//打印locations:[94043,90210]
●JSONException:是JSON.org类抛出的异常信息→如果JSONObject中存取的不是键值对形式的数据会抛出此异常
◎小案例^0^
1.首先获得json数据源,懒得自己创建服务器,就用了豆瓣的api,地址:http://api.douban.com/book/subject/isbn/9787111187776,这个得到的是一个xml文档,在地址后面加上参数"?alt=json",即可得到该文档的json数据;由于数据较多……下面只获取部分
点击(此处)折叠或打开
- {
- "category":
- {
- "@scheme":"http:\/\/www.douban.com\/2007#kind",
- "@term":"http:\/\/www.douban.com\/2007#book"
- },
- "db:tag":
- [
- {"@count":3182,"@name":"算法"},
- {"@count":1798,"@name":"算法导论"},
- {"@count":1368,"@name":"计算机"},
- {"@count":1046,"@name":"编程"},
- {"@count":790,"@name":"经典"},
- {"@count":717,"@name":"algorithm"},
- {"@count":558,"@name":"计算机科学"},
- {"@count":443,"@name":"程序设计"}
- ],
- "title":
- {"$t":"算法导论"},
- "author":
- [{"name":{"$t":"[美] Thomas H.Cormen"}},{"name":{"$t":"Charles E.Leiserson"}},
- {"name":{"$t":"Ronald L.Rivest"}},{"name":{"$t":"Clifford Stein"}}],
- "summary":
- {"$t":"这本书深入浅出,全面地介绍了计算机算法。对每一个算法的分析既易于理解又十分有趣,并保持了数学严谨性。本书的设计目标全面,适用于多种用途。涵盖的内容有:算法在计算中的作用,概率分析和随机算法的介绍。书中专门讨论了线性规划,介绍了动态规划的两个应用,随机化和线性规划技术的近似算法等,还有有关递归求解、快速排序中用到的划分方法与期望线性时间顺序统计算法,以及对贪心算法元素的讨论。此书还介绍了对强连通子图算法正确性的证明,对哈密顿回路和子集求和问题的NP完全性的证明等内容。全书提供了900多个练习题和思考题以及叙述较为详细的实例研究。"},
- "link":
- [
- {"@rel":"self","@href":"http:\/\/api.douban.com\/book\/subject\/1885170"},
- {"@rel":"alternate","@href":"http:\/\/book.douban.com\/subject\/1885170\/"},
- {"@rel":"image","@href":"http:\/\/img3.douban.com\/spic\/s1959967.jpg"},
- {"@rel":"mobile","@href":"http:\/\/m.douban.com\/book\/subject\/1885170\/"}
- ],
- "db:attribute":
- [
- {"$t":"7111187776","@name":"isbn10"},
- {"$t":"9787111187776","@name":"isbn13"},
- {"$t":"Thomas H.Cormen\n达特茅斯学院计算机科学系副教授\nCharles E.Leiserson\n麻省理工学院计算机科学与电气工程系教授\nRonald L.Rivest\n麻省理工学院计算机科学系 Andrew与Erna Viterbi具名教授\nClifford Stein\n哥伦比亚大学工业工程与运筹学副教授","@name":"author-intro"},
- {"$t":"754","@name":"pages"},
- {"$t":"潘金贵 等","@name":"translator"},
- {"$t":"[美] Thomas H.Cormen","@name":"author"},
- {"$t":"Charles E.Leiserson","@name":"author"},
- {"$t":"Ronald L.Rivest","@name":"author"},
- {"$t":"Clifford Stein","@name":"author"},
- {"$t":"85.00元","@name":"price"},
- {"$t":"机械工业出版社","@name":"publisher"},
- {"$t":"平装","@name":"binding"},
- {"$t":"2006-9","@name":"pubdate"},
- {"$t":"Introduction to Algorithms","@name":"aka"},
- {"$t":"算法导论","@name":"title"}
- ],
- "id":
- {"$t":"http:\/\/api.douban.com\/book\/subject\/1885170"},
- "gd:rating":{"@min":0,"@numRaters":3725,"@average":"9.4","@max":10}
- }
2.创建Android项目,编写布局文件main.xml:用tablerow布局方便显示
点击(此处)折叠或打开
- <?xml version="1.0" encoding="utf-8"?>
- <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <TableLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="标题" />
- <TextView
- android:id="@+id/tv_title"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="标签 :" />
- <TextView
- android:id="@+id/tv_tag"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="作者" />
- <TextView
- android:id="@+id/tv_author"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="页数" />
- <TextView
- android:id="@+id/tv_pages"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="价格" />
- <TextView
- android:id="@+id/tv_price"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="简介" />
- <TextView
- android:id="@+id/tv_summary"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- </TableLayout>
- <LinearLayout
- android:id="@+id/ll_book_detail"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@android:color/background_dark"
- android:gravity="center"
- android:visibility="invisible"
- >
- <ProgressBar
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </LinearLayout>
- </FrameLayout>
3.编写activity文件;
点击(此处)折叠或打开
- <?xml version="1.0" encoding="utf-8"?>
- <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <TableLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="标题" />
- <TextView
- android:id="@+id/tv_title"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="标签 :" />
- <TextView
- android:id="@+id/tv_tag"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="作者" />
- <TextView
- android:id="@+id/tv_author"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="页数" />
- <TextView
- android:id="@+id/tv_pages"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="价格" />
- <TextView
- android:id="@+id/tv_price"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- <TableRow
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="简介" />
- <TextView
- android:id="@+id/tv_summary"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- </TableLayout>
- <LinearLayout
- android:id="@+id/ll_book_detail"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@android:color/background_dark"
- android:gravity="center"
- android:visibility="invisible"
- >
- <ProgressBar
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </LinearLayout>
- </FrameLayout>
点击(此处)折叠或打开
- public class JsonProjectActovoty extends Activity {
- /** Called when the activity is first created. */
- //定义相关控件
- TextView tv_title,tv_tag,tv_pages;
- TextView tv_summary,tv_author,tv_price;
- LinearLayout ll_layout;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.book_detail);
- //初始化相关控件
- tv_title= (TextView)this.findViewById(R.id.tv_title);
- tv_summary = (TextView)this.findViewById(R.id.tv_summary);
- tv_author = (TextView)this.findViewById(R.id.tv_author);
- tv_tag=(TextView)this.findViewById(R.id.tv_tag);
- tv_pages = (TextView)this.findViewById(R.id.tv_pages);
- tv_price = (TextView)this.findViewById(R.id.tv_price);
- ll_layout = (LinearLayout)this.findViewById(R.id.ll_book_detail);
- //代码量较多,则编写在另一个方法中
- getJsonData();
- }
- private void getJsonData() {
- //网络下载数据相对耗时,使用异步加载,减少主线程负担
- new AsyncTask<String, Void, Boolean>() {
- String title;
- String summary ;
- String tag;
- String author,pages,price;
- @Override
- protected void onPreExecute() {
- // TODO Auto-generated method stub
- //显示进度条
- ll_layout.setVisibility(View.VISIBLE);
- super.onPreExecute();
- }
- @Override
- protected void onPostExecute(Boolean result) {
- // TODO Auto-generated method stub
- //设置进度条消失
- ll_layout.setVisibility(View.INVISIBLE);
- //如果获取到数据则把数据显示到屏幕
- if (result) {
- tv_title.setText(title);
- tv_summary.setText(summary);
- tv_tag.setText(tag);
- tv_author.setText(author);
- tv_pages.setText(pages);
- tv_price.setText(price);
- }else {
- Toast.makeText(getApplicationContext(),"获取数据失败",0).show();
- }
- super.onPostExecute(result);
- }
- @Override
- protected Boolean doInBackground(String... params) {
- // TODO Auto-generated method stub
- String path = "http://api.douban.com/book/subject/isbn/9787111187776?alt=json";
- try {
- URL url = new URL(path);
- Source source = new Source(url.openConnection());//这个需加入jericho-html-3.1.jar包
- String jsonstr = source.toString();
- //得到一个JSONObject对象
- JSONObject jsonObj = new JSONObject(jsonstr);
- //获取title
- String titlestr = jsonObj.get("title").toString();
- JSONObject jsontitle = new JSONObject(titlestr);
- title = jsontitle.getString("$t");
-
- //获取标签
- String tagstr = jsonObj.getString("db:tag");
- JSONArray jsonArray = new JSONArray(tagstr);
- StringBuffer sb = new StringBuffer();
- String tagarr = null;
- for (int i = 0; i < jsonArray.length(); i++) {
- tagarr = jsonArray.getString(i);
- JSONObject jsonObject = new JSONObject(tagarr);
- tag = jsonObject.getString("@name");
- sb.append(tag+"/");
- }
- tag =sb.substring(0, sb.length()-1);
-
- //获取作者
- String authorstr = jsonObj.getString("author");
- JSONArray authorArray = new JSONArray(authorstr);
- StringBuffer sbauthor = new StringBuffer();
- String authorarr = null;
- for (int i = 0; i < authorArray.length(); i++) {
- System.out.println(authorArray.length());
- authorarr = authorArray.getString(i);
- JSONObject jsonObject = new JSONObject(authorarr);
- String authorName = jsonObject.getString("name");
- jsonObject = new JSONObject(authorName);
- author = jsonObject.getString("$t");
- sbauthor.append(author+"/");
- }
- author =sbauthor.substring(0, sbauthor.length()-1);
-
- //获取价格与页数
- String str = jsonObj.getString("db:attribute");
- JSONArray array = new JSONArray(str);
- sb = new StringBuffer();
- String bookinfo = null;
- for (int i = 0; i < array.length(); i++) {
- bookinfo = array.getString(i);
- JSONObject jsonObject = new JSONObject(bookinfo);
- if ("price".equals(jsonObject.getString("@name"))) {
- price = jsonObject.getString("$t");
- }
- if ("pages".equals(jsonObject.getString("@name"))) {
- pages = jsonObject.getString("$t");
- }
- }
- //获取简介
- String summarystr = jsonObj.getString("summary");
- JSONObject jsonsummary = new JSONObject(summarystr);
- summary = jsonsummary.getString("$t");
- return true;
- } catch (Exception e) {
- Toast.makeText(getApplicationContext(), "获取数据失败", 0).show();
- return false;
- }
- }
- }.execute();
- }
- }
3.最后不要忘了加入访问网络的权限;运行程序可看到
0 0
- Json方式获取网络数据
- Volley 重写源码,使用Post方式获取网络Json数据
- RxVolley进行网络请求(get方式),获取json数据
- JSON异步获取网络数据
- 网络中获取json数据
- JSON数据获取的三种方式
- flask post JSON 数据获取方式总结
- Android获取网络XML/JSON数据
- 从网络获取JSON格式数据
- 获取网络上的json数据
- Volley 库通过网络获取 JSON 数据
- Android:网络:获取JSON格式数据
- 用异步获取网络数据Json
- 从网络接口获取json数据不完全
- Android 网络获取数据之Json解析
- 获取网络数据(Json串和图片)
- 获取网络Json格式数据-使用原生态解析Json
- android Poast方式获取数据网络不稳定
- Java事务处理总结
- 第16周OJ-3
- 【目标检测】Fast RCNN算法详解
- javascript判断变量是否为空的方法
- 笔记:常用的几个小片段
- Json方式获取网络数据
- win10内部错误2502,2503最有效的解决方案!
- Spring MVC 入门指南(一):HelloWorld
- c++ 时间函数使用
- 第十七周-OJ-B指针变量交换
- 几种简单的负载均衡算法及其Java代码实现
- setTimeout立即执行,没有延迟效果
- 第一行代码之详解四种基本布局
- Windows 2003 汉化