解析JSON_图书索引下载案例

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,常用于 JavaScript 的数据交换,现在已经逐渐成为一种与语言无关的数据交换格式,这一点类似于XML,但要比 XML 更加轻量级。

Andorid 集成了对 JSON 的支持,与 JSON 相关的类在 org.json 包中,主要有 JSONArray、JSONObject、JSONString 等。通过这些类就可以很轻松地实现 JSON 字符串与 JSONOject 和 JSONArray 直接的相互转换。

JSON 与 XML 的使用建议:

1、JSON 使用格式比较简单,其主战场在 Web 开发的前端,即 JavaScript 的应用场景;XML 格式更加规范,可扩展性较强。

2、JSON 和 XML 的轻/重量级的区别在于:JSON 只提供了整体解决方案,而这种方法只在解析较少的数据时才能起到良好的效果;而 XML 提供了对大规模数据的逐步解析方案,这种方案很适用于对大量数据的处理。

3、传输数量较少时建议使用 JSON,当数据量较大时建议使用 XML。

 

 Android 客户端

  1 import java.io.IOException;
  2 import java.io.UnsupportedEncodingException;
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 
  6 import org.apache.http.HttpResponse;
  7 import org.apache.http.NameValuePair;
  8 import org.apache.http.client.ClientProtocolException;
  9 import org.apache.http.client.HttpClient;
 10 import org.apache.http.client.entity.UrlEncodedFormEntity;
 11 import org.apache.http.client.methods.HttpPost;
 12 import org.apache.http.impl.client.DefaultHttpClient;
 13 import org.apache.http.message.BasicNameValuePair;
 14 import org.apache.http.protocol.HTTP;
 15 import org.apache.http.util.EntityUtils;
 16 import org.json.JSONArray;
 17 import org.json.JSONException;
 18 import org.json.JSONObject;
 19 import org.json.JSONTokener;
 20 
 21 import com.freshen.entity.Book;
 22 
 23 import android.os.Bundle;
 24 import android.os.Handler;
 25 import android.os.Message;
 26 import android.app.Activity;
 27 import android.util.Log;
 28 import android.view.Menu;
 29 import android.view.View;
 30 import android.view.View.OnClickListener;
 31 import android.widget.Button;
 32 import android.widget.EditText;
 33 import android.widget.TextView;
 34 
 35 public class MainActivity extends Activity implements OnClickListener{
 36     
 37     EditText et;
 38     Button bt;
 39     TextView tv;
 40     HttpClient httpClient = new DefaultHttpClient();
 41     
 42     Handler handler = new Handler(){
 43         @Override
 44         public void handleMessage(Message msg) {
 45             super.handleMessage(msg);
 46             
 47             tv.append(msg.obj.toString()+"\n");
 48         }
 49     };
 50     
 51     @Override
 52     protected void onCreate(Bundle savedInstanceState) {
 53         super.onCreate(savedInstanceState);
 54         
 55         setContentView(R.layout.activity_main);
 56         et = (EditText) findViewById(R.id.et);
 57         tv = (TextView) findViewById(R.id.tv);
 58         bt = (Button) findViewById(R.id.bt);
 59         bt.setOnClickListener(this);
 60     }
 61     
 62     @Override
 63     public void onClick(View v) {
 64         String id = et.getText().toString();
 65         if(id.length()>0)getBookFromNet(id);
 66     }
 67     
 68     public void getBookFromNet(final String id){
 69         
 70         final String urlStr = "http://192.168.1.103:8080/part10_7_7/servlet/GetBook";
 71         
 72         new Thread(new Runnable(){
 73             
 74             @Override
 75             public void run() {
 76                 
 77                 HttpPost post = new HttpPost(urlStr);
 78                 List<NameValuePair> params = new ArrayList<NameValuePair>();
 79                 params.add(new BasicNameValuePair("id",id));
 80                 
 81                 try {
 82                     post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
 83                     HttpResponse httpResponse = httpClient.execute(post);
 84                     int code = httpResponse.getStatusLine().getStatusCode();
 85                     Log.i("Tag", "服务器返回码 " + code);
 86                     String msg;
 87                     
 88                     if(code == 200){
 89                         // 8、读取数据,EntityUtils是工具类,可以读取 Entity 中字符串内容
 90                         msg = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
 91                         Log.i("Tag", "未经解析的服务器返回的Json字符串 "+msg);
 92                         // Handler 通知主 UI 更新
 93                         Message message = new Message();
 94                         message.obj = msg;
 95                         handler.sendMessage(message);
 96                         //将收到的 JSON 串转换为 Java 对象
 97                         JSONArray jsonArray = new JSONArray(msg);
 98                         // 因为只有一个对象
 99                         JSONObject jsonObj = jsonArray.getJSONObject(0);
100                         Book book = new Book();
101                         book.setId(jsonObj.getString("id"));
102                         book.setBookName(jsonObj.getString("bookName"));
103                         book.setBookPrice(jsonObj.getString("bookPrice"));
104                         Log.i("Tag", "已经解析为Book对象的字符串  " + book.toString());
105                         //Handler 通知主 UI 更新
106                         Message message2 = new Message();
107                         message2.obj = book.toString();
108                         handler.sendMessage(message2);
109                     }else{
110                         msg = "访问服务器错误!";
111                         // Handler 通知主 UI 更新
112                         Message message = new Message();
113                         message.obj = msg;
114                         handler.sendMessage(message);
115                     }
116 
117                 } catch (UnsupportedEncodingException e) {
118                     // TODO Auto-generated catch block
119                     e.printStackTrace();
120                 } catch (ClientProtocolException e) {
121                     // TODO Auto-generated catch block
122                     e.printStackTrace();
123                 } catch (IOException e) {
124                     // TODO Auto-generated catch block
125                     e.printStackTrace();
126                 } catch (JSONException e) {
127                     // TODO Auto-generated catch block
128                     e.printStackTrace();
129                 }
130             }
131         }).start();
132     }
133 }
MainActivity

Book.java

 1 public class Book {
 2     
 3     private String id, bookName, bookPrice;
 4     public Book(){}
 5     
 6     public Book(String id, String bookName, String bookPrice) {
 7         super();
 8         
 9         this.id = id;
10         this.bookName = bookName;
11         this.bookPrice = bookPrice;
12     }
13 
14     public String getId() {
15         return id;
16     }
17 
18     public void setId(String id) {
19         this.id = id;
20     }
21 
22     public String getBookName() {
23         return bookName;
24     }
25 
26     public void setBookName(String bookName) {
27         this.bookName = bookName;
28     }
29 
30     public String getBookPrice() {
31         return bookPrice;
32     }
33 
34     public void setBookPrice(String bookPrice) {
35         this.bookPrice = bookPrice;
36     }
37 
38     @Override
39     public String toString() {
40         return "Book [编号=" + id + ", 书名=" + bookName + ", 单价="
41                 + bookPrice + "]";
42     }
43     
44 }
Book.java

布局文件

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:paddingBottom="@dimen/activity_vertical_margin"
 6     android:paddingLeft="@dimen/activity_horizontal_margin"
 7     android:paddingRight="@dimen/activity_horizontal_margin"
 8     android:paddingTop="@dimen/activity_vertical_margin"
 9     tools:context=".MainActivity" >
10     
11       <LinearLayout
12         android:layout_width="fill_parent"
13         android:layout_height="wrap_content"
14         android:orientation="horizontal"
15         android:id="@+id/layout"
16         >
17         
18         <TextView
19         android:layout_width="wrap_content"
20         android:layout_height="wrap_content"
21         android:text="查询ID:" />
22         
23         <EditText 
24             android:layout_width="wrap_content"
25             android:layout_height="wrap_content"
26             android:inputType="number"
27             android:id="@+id/et"
28             android:layout_weight="1.0"
29             />
30         
31         <Button 
32             android:layout_width="wrap_content"
33             android:layout_height="wrap_content"
34             android:text="查询"
35             android:id="@+id/bt"
36             />
37         
38     </LinearLayout>
39     
40     <TextView
41         android:id="@+id/tv"
42         android:layout_width="wrap_content"
43         android:layout_height="wrap_content"
44         android:layout_below="@id/layout"
45         android:text="" />
46 
47   
48 
49 </RelativeLayout>
activity_main.xml

添加网络权限

<uses-permission android:name="android.permission.INTERNET"/>

服务端采用 HttpClient 访问 Web Servlet,获取 JSON 字符串,然后封装成 Java 对象。服务端要引用 json.jar(org.json)插件。需要特别注意的是,JSONArray 构造方法的参数只能是 List 集合、数组、字符串等,不能传入 Map 集合。

 1 public class Book {
 2     
 3     private String id, bookName, bookPrice;
 4     public Book(){}
 5     
 6     public Book(String id, String bookName, String bookPrice) {
 7         
 8         super();
 9         this.id = id;
10         this.bookName = bookName;
11         this.bookPrice = bookPrice;
12     }
13 
14     public String getId() {
15         return id;
16     }
17 
18     public void setId(String id) {
19         this.id = id;
20     }
21 
22     public String getBookName() {
23         return bookName;
24     }
25 
26     public void setBookName(String bookName) {
27         this.bookName = bookName;
28     }
29 
30     public String getBookPrice() {
31         return bookPrice;
32     }
33 
34     public void setBookPrice(String bookPrice) {
35         this.bookPrice = bookPrice;
36     }
37 
38     @Override
39     public String toString() {
40         return "Book [id=" + id + ", bookName=" + bookName + ", bookPrice="
41                 + bookPrice + "]";
42     }
43     
44 }
Book.java

SearchBookServlet.java

 1 import java.io.IOException;
 2 import java.io.PrintWriter;
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 import javax.servlet.ServletException;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 import org.json.JSONArray;
14 import org.json.JSONException;
15 import org.json.JSONObject;
16 
17 import com.freshen.entity.Book;
18 
19 public class SearchBookServlet extends HttpServlet {
20     
21     Map<String,Book> books = new HashMap<String,Book>();
22     
23     @Override
24     public void init() throws ServletException {
25         
26         super.init();
27         books.put("1", new Book("1001","Java核心技术","88.5"));
28         books.put("2", new Book("1002","Android应用程序开发教程","38"));
29         books.put("3", new Book("1003","Android游戏开发基础","48"));
30         books.put("4", new Book("1004","Java Web开发高级教程","66"));
31         books.put("5", new Book("1005","Android操作系统内核解密","45"));
32     }
33     
34     public void doGet(HttpServletRequest request, HttpServletResponse response)
35             throws ServletException, IOException {
36         
37         doPost(request,response);
38     }
39     
40     public void doPost(HttpServletRequest request, HttpServletResponse response)
41             throws ServletException, IOException {
42         
43         response.setCharacterEncoding("UTF-8");
44         response.setContentType("text/html");
45         
46         String id = request.getParameter("id");
47         List<Book> bs = new ArrayList<Book>();
48         bs.add(books.get(id));
49         
50         // 将 Java 对象转换为 JSON 串
51         JSONArray jsonArray = new JSONArray(bs);
52         String jsonStr;
53         jsonStr = jsonArray.toString();
54         System.out.println(jsonStr);
55         PrintWriter out = response.getWriter();
56         out.println(jsonStr);
57         out.flush();
58         out.close();
59     }
60 
61 }
SearchBookServlet

Test.java

 1 import java.util.ArrayList;
 2 import java.util.HashMap;
 3 import java.util.List;
 4 import java.util.Map;
 5 
 6 import org.json.JSONArray;
 7 import org.json.JSONException;
 8 import org.json.JSONObject;
 9 
10 import com.freshen.entity.Book;
11 
12 public class Test {
13     
14     Map<String,Book> books = new HashMap<String,Book>();
15     
16     public Test(){
17         
18         books.put("1", new Book("1001","Java核心技术","88.5"));
19         books.put("2", new Book("1002","Android应用程序开发教程","38"));
20         books.put("3", new Book("1003","Android游戏开发基础","48"));
21         books.put("4", new Book("1004","Java Web开发高级教程","66"));
22         books.put("5", new Book("1005","Android操作系统内核解密","45"));
23         
24         Book bk = books.get("1");
25         List bks = new ArrayList();
26         bks.add(bk);
27 
28         JSONArray jsa = new JSONArray(bks);
29         String js = jsa.toString();
30         System.out.println(js);
31         
32         try {
33             JSONArray ja = new JSONArray(js);
34             JSONObject jo = ja.getJSONObject(0);
35             
36             System.out.println(ja.length());
37             System.out.println(jo.getString("bookName"));
38             
39         } catch (JSONException e) {
40             // TODO Auto-generated catch block
41             e.printStackTrace();
42         }        
43     }
44         
45     public static void main(String[] args) {
46         
47         new Test();
48     }
49 }
Test.java

 

posted @ 2015-05-24 13:22  壬子木  阅读(299)  评论(0)    收藏  举报