- package com.zml.pojo;
- /**
- * @author 郑明亮
- * @Time:2016年2月2日 下午10:35:05
- * @version 1.0
- */
- public class Person {
- String name;
- String sex;
- String QQ;
- String contact;
- public Person() {
- // TODO Auto-generated constructor stub
- }
- public Person(String name, String sex, String qQ, String contact) {
- super();
- this.name = name;
- this.sex = sex;
- QQ = qQ;
- this.contact = contact;
- }
- /**
- * @return the name
- */
- public String getName() {
- return name;
- }
- /**
- * @param name
- * the name to set
- */
- public void setName(String name) {
- this.name = name;
- }
- /**
- * @return the sex
- */
- public String getSex() {
- return sex;
- }
- /**
- * @param sex
- * the sex to set
- */
- public void setSex(String sex) {
- this.sex = sex;
- }
- /**
- * @return the qQ
- */
- public String getQQ() {
- return QQ;
- }
- /**
- * @param qQ
- * the qQ to set
- */
- public void setQQ(String qQ) {
- QQ = qQ;
- }
- /**
- * @return the contact
- */
- public String getContact() {
- return contact;
- }
- /**
- * @param contact
- * the contact to set
- */
- public void setContact(String contact) {
- this.contact = contact;
- }
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return "Person [name=" + name + ", sex=" + sex + ", QQ=" + QQ
- + ", contact=" + contact + "]";
- }
- }
2.我写了一个工具类,用来生成上述的四种类型的数据;
- package com.zml.utils;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import com.zml.pojo.Person;
- /**
- * 用于生成四种类型的数据来测试json解析:
- * ①Person对象类型 ②List<Person> ③List<String> ④List<Map<String,Object>>
- *
- * @author 郑明亮
- * @Time:2016年2月2日 下午10:38:40
- * @version 1.0
- */
- public class DataUtil {
- public static Person getPerson() {
- return new Person("郑明亮", "男", "1072307340", "15733100573");
- }
- public static List<Person> getPersons() {
- List<Person> list = new ArrayList<Person>();
- list.add(getPerson());
- list.add(new Person("张三", "男", "123456789", "98765432"));
- list.add(new Person("李四", "女", "762348234", "12312124324"));
- return list;
- }
- public static List<String> getStrings(){
- List<String>list = new ArrayList<String>();
- list.add("郑明亮");
- list.add("张三");
- list.add("李四");
- return list;
- }
- public static List<Map<String,Object>> getMaps(){
- List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
- Map<String,Object> map = new HashMap<String, Object>();
- map.put("name","郑明亮" );
- map.put("blog", "blog.csdn.net/zml_2015");
- map.put("person", getPerson());
- list.add(map);
- return list;
- }
- }
3.接下来就是写json数据类型的转换类了
- package com.zml.utils;
- import net.sf.json.JSONObject;
- /**
- * @author 郑明亮
- * @Time:2016年2月2日 上午12:18:38
- * @version 1.0
- */
- public class JsonTools {
- public static String createJsonString(String key,Object value){
- JSONObject jsonObject=new JSONObject();
- jsonObject.put(key, value);
- return jsonObject.toString();
- }
- }
4.进行测试,看是否将上述4种数据转换为了json的数据类型
- package com.zml.test;
- import com.zml.utils.DataUtil;
- import com.zml.utils.JsonTools;
- /**
- * @author 郑明亮
- * @Time:2016年2月2日 上午12:27:29
- * @version 1.0
- */
- public class testjson {
- public static void main(String[] args) {
- String jsonString;
- jsonString = JsonTools.createJsonString("person",DataUtil.getPerson());
- System.out.println(jsonString);
- jsonString = JsonTools.createJsonString("persons",DataUtil.getPersons());
- System.out.println(jsonString);
- jsonString = JsonTools.createJsonString("strings",DataUtil.getStrings());
- System.out.println(jsonString);
- jsonString = JsonTools.createJsonString("maps",DataUtil.getMaps());
- System.out.println(jsonString);
- }
- }
5.测试成功后,建立Servlet类,以方便将json数据传输给客户端
- <p>package com.zml.test;</p><p>import java.io.IOException;
- import java.io.PrintWriter;</p><p>import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;</p><p>import com.zml.utils.DataUtil;
- import com.zml.utils.JsonTools;</p><p>/**
- * @author 郑明亮
- * @Time:2016年2月2日 下午10:54:26
- * @version 1.0
- */
- public class JsonServlet extends HttpServlet {</p><p> /**
- * Constructor of the object.
- */
- public JsonServlet() {
- super();
- }</p><p> /**
- * Destruction of the servlet. <br>
- */
- public void destroy() {
- super.destroy(); // Just puts "destroy" string in log
- // Put your code here
- }</p><p> /**
- * The doGet method of the servlet. <br>
- *
- * This method is called when a form has its tag value method equals to get.
- *
- * @param request
- * the request send by the client to the server
- * @param response
- * the response send by the server to the client
- * @throws ServletException
- * if an error occurred
- * @throws IOException
- * if an error occurred
- */
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doPost(request, response);</p><p> }</p><p> /**
- * The doPost method of the servlet. <br>
- *
- * This method is called when a form has its tag value method equals to
- * post.
- *
- * @param request
- * the request send by the client to the server
- * @param response
- * the response send by the server to the client
- * @throws ServletException
- * if an error occurred
- * @throws IOException
- * if an error occurred
- */
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {</p><p> response.setContentType("text/html;charset=utf-8");
- request.setCharacterEncoding("utf-8");
- response.setCharacterEncoding("utf-8");
- PrintWriter out = response.getWriter();</p><p> String jsonString="";
- String actionString = request.getParameter("action");
- if (actionString.equals("person")) {
- jsonString = JsonTools.createJsonString("person",DataUtil.getPerson());</p><p> } else if (actionString.equals("persons")) {
- jsonString = JsonTools.createJsonString("persons",DataUtil.getPersons());</p><p> } else if (actionString.equals("strings")) {
- jsonString = JsonTools.createJsonString("strings",DataUtil.getStrings());</p><p> } else if (actionString.equals("maps")) {
- jsonString = JsonTools.createJsonString("maps",DataUtil.getMaps());
- }
- out.write(jsonString);</p><p> }</p><p> /**
- * Initialization of the servlet. <br>
- *
- * @throws ServletException
- * if an error occurs
- */
- public void init() throws ServletException {
- // Put your code here
- }</p><p>}
- </p>
通过网址访问可得到的JSON数据:
二、客户端解析json数据
这里暂时只贴出重要的解析部分,
- package com.zml.util;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import com.zml.pojo.Person;
- /**
- * 解析数据:将json字符串解析还原成原来的数据类型
- *
- * @author 郑明亮
- * @date 2016-2-3 上午12:11:57
- * @version 1.0
- */
- public class JsonTools {
- public static Person getPerson(String key, String jsonString) {
- Person person = new Person();
- // 将json字符串转换成json对象
- try {
- JSONObject jsonObject = new JSONObject(jsonString);
- // 将json对象根据key(person),拿到对应的value(Person对象)值
- JSONObject jsonObject2 = jsonObject.getJSONObject(key);
- // 将拿到的对象set到一个person对象中
- person.setName(jsonObject2.getString("name"));
- person.setSex(jsonObject2.getString("sex"));
- person.setQQ(jsonObject2.getString("QQ"));
- person.setContact(jsonObject2.getString("contact"));
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return person;
- }
- public static List<Person> getPersons(String key, String jsonString) {
- List<Person> list = new ArrayList<Person>();
- JSONObject jsonObject;
- try {
- jsonObject = new JSONObject(jsonString);
- JSONArray Persons = jsonObject.getJSONArray(key);
- for (int i = 0; i < Persons.length(); i++) {
- Person person = new Person();
- JSONObject jsonObject2 = Persons.getJSONObject(i);
- person.setName(jsonObject2.getString("name"));
- person.setSex(jsonObject2.getString("sex"));
- person.setQQ(jsonObject2.getString("QQ"));
- person.setContact(jsonObject2.getString("contact"));
- list.add(person);
- }
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return list;
- }
- public static List<String> getStrings(String key, String jsonString) {
- List<String> list = new ArrayList<String>();
- try {
- JSONObject jsonObject = new JSONObject(jsonString);
- JSONArray StringArray = jsonObject.getJSONArray(key);
- for (int i = 0; i < StringArray.length(); i++) {
- String str = StringArray.getString(i);
- list.add(str);
- }
- } catch (Exception e) {
- // TODO: handle exception
- }
- return list;
- }
- public static List<Map<String, Object>> getMaps(String key,
- String jsonString) {
- List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
- try {
- JSONObject jsonObject = new JSONObject(jsonString);
- JSONArray mapsArray = jsonObject.getJSONArray(key);
- for (int i = 0; i < mapsArray.length(); i++) {
- JSONObject jsonObject2 = mapsArray.getJSONObject(i);
- Map<String, Object> map = new HashMap<String, Object>();
- // 查看Map中的键值对的key值
- Iterator<String> iterator = jsonObject2.keys();
- while (iterator.hasNext()) {
- String json_key = iterator.next();
- Object json_value = jsonObject2.get(json_key);
- if(json_value==null){
- //当键值对中的value为空值时,将value置为空字符串;
- json_value="";
- }
- map.put(json_key, json_value);
- }
- list.add(map);
- }
- } catch (Exception e) {
- // TODO: handle exception
- }
- return list;
- }
- }
需要注意的是上述,客户端和服务器端虽然都用到了JSONObject类,但是引用的不是一个jar包中的内容哦;客户端的是引用的 org.json.JSONObject;而服务器端引用的是net.sf.json.JSONObject;