zoukankan      html  css  js  c++  java
  • Json入门

    参考《疯狂android讲义》》730页


    JSON的基础请参考W3SCHOOL的教程:

    http://www.w3school.com.cn/json/index.asp


    例子:

    http://wenku.baidu.com/link?url=A5SiKBUNVx-aB_hFiDuHsEN1uw_Vu4a9ODRq7G-SpiY-qW11Ve8Ba8ym9TfheAUuHJhYgdD3g05lvGNWrPBzf7JZFhUlAcZYb0MMIdrcmp3

    1、创建服务器端:

    (1)创建对象类

    package com.ljh.jsondemo.model;
    
    public class User {
    	
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getEmail() {
    		return email;
    	}
    	public void setEmail(String email) {
    		this.email = email;
    	}
    	public String getGender() {
    		return gender;
    	}
    	public void setGender(String gender) {
    		this.gender = gender;
    	}
    	private int id;
    	private String name;
    	private String email;
    	private String gender;  
    }
    


    (2)创建json的提供类

    package com.ljh.jsondemo.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    import com.ljh.jsondemo.model.User;
    
    public class JsonDemoServlet extends HttpServlet {
    
    	private static final long serialVersionUID = -7368225680407826408L;
    
    	private List<User> list;
    
    	/** * 处理post方式提交的数据 */
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    
    	throws ServletException, IOException {
    		doGet(request, response);
    
    	}
    
    	/** * 处理get方式提交的数据 */
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    
    	throws ServletException, IOException {
    
    		response.setContentType("text/plain");
    
    		response.setCharacterEncoding("UTF-8");
    
    		PrintWriter out = response.getWriter();
    
    		// 准备用户数据
    
    		prepareData();
    
    		// JSON数组
    
    		JSONArray array = new JSONArray();
    
    		for (User bean : list) {
    
    			// 单个用户JSON对象
    
    			JSONObject obj = new JSONObject();
    
    			try {
    				obj.put("id", bean.getId());
    
    				obj.put("name", bean.getName());
    
    				obj.put("email", bean.getEmail());
    
    				obj.put("gender", bean.getGender());
    
    			}
    
    			catch (Exception e) {
    			}
    
    			array.put(obj);
    
    		}
    
    		// 输出
    
    		out.write(array.toString());
    
    		out.flush();
    		out.close();
    	}
    
    	private void prepareData() {
    
    		list = new ArrayList<User>();
    
    		User bean1 = new User();
    
    		bean1.setId(1001);
    
    		bean1.setName("Tony");
    
    		bean1.setEmail("");
    
    		bean1.setGender("male");
    
    		list.add(bean1);
    
    		User bean2 = new User();
    
    		bean2.setId(1002);
    
    		bean2.setName("Jack");
    
    		bean2.setEmail("");
    
    		bean2.setGender("male");
    
    		list.add(bean2);
    
    		User bean3 = new User();
    
    		bean3.setId(1003);
    
    		bean3.setName("Marry");
    
    		bean3.setEmail("");
    
    		bean3.setGender("female");
    
    		list.add(bean3);
    
    		User bean4 = new User();
    
    		bean4.setId(1004);
    
    		bean4.setName("Linda");
    
    		bean4.setEmail("");
    
    		bean4.setGender("female");
    
    		list.add(bean4);
    
    	}
    
    }
    

    2、创建android客户端

    注意要添加访问internet的权限。

    package com.ljh.jsondemoclient;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
    
    	
    
    	private String getContent(String url) throws Exception {
    
    		StringBuilder sb = new StringBuilder();
    
    		HttpClient client = new DefaultHttpClient();
    
    		HttpParams httpParams = client.getParams();
    
    		// 设置网络超时参数
    
    		HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
    
    		HttpConnectionParams.setSoTimeout(httpParams, 5000);
    
    		HttpResponse response = client.execute(new HttpGet(url));
    
    		HttpEntity entity = response.getEntity();
    
    		if (entity != null) {
    			System.out.println("test!!!!");
    
    			BufferedReader reader = new BufferedReader(new InputStreamReader(
    					entity.getContent(), "UTF-8"), 8192);
    
    			String line = null;
    
    			while ((line = reader.readLine()) != null) {
    
    				sb.append(line + "
    ");
    
    			}
    
    			reader.close();
    
    		}
    		return sb.toString();
    
    	}
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		try {
    
    			StringBuffer sb = new StringBuffer();
    
    			// 在测试过程中,经常是用本机做测试服务器,访问本机的IP地址要设置为10.0.2.2
    
    			String url = "192.168.136.133:8080/JsonDemoServer/JsonDemoServlet";
    
    			String body = getContent(url);
    
    			JSONArray array = new JSONArray(body);
    
    			for (int i = 0; i < array.length(); i++) {
    
    				JSONObject obj = array.getJSONObject(i);
    
    				sb.append("id:").append(obj.getInt("id")).append("	");
    
    				sb.append("name:").append(obj.getString("name")).append("
    ");
    
    				sb.append("gender:").append(obj.getString("gender"))
    						.append("	");
    
    				sb.append("email:").append(obj.getString("email"))
    						.append("
    ");
    
    				sb.append("----------------------
    ");
    
    			}
    
    			TextView textView = (TextView) findViewById(R.id.tv_json_content);
    
    			textView.setText(sb.toString());
    
    		} catch (Exception e) {
    		}
    	}
    }


  • 相关阅读:
    Linux系统-命令行快捷键
    Golang理解-Context包
    Golang理解-垃圾回收机制
    Linux系统-Systemd资源控制
    Linux系统-"cannot access Input/output error"
    Linux系统-ntpdate时间同步报错
    Golang理解-数组和切片
    Golang理解-位运算
    Golang理解-指针
    Maven配置,使用IntelliJ IDEA和Maven创建Java Web项目
  • 原文地址:https://www.cnblogs.com/eaglegeek/p/4557949.html
Copyright © 2011-2022 走看看