Json类型数据可以通过Json官方提供的方法将Json字符串转化为对象类型,但是解析往往比较麻烦,

Gson是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来

谷歌提供的Gson解析Json往往比Json解析更出色,更简单

在这里我写四个通用方法,将最常用的四种数据类型通过Gson将json数据解析还原为对象类型,List包裹对象类型,List包裹字符串类型,List包裹map类型。

 

如果没有看我的Android客户端与服务器端交互数据之json解析,有些类的调用省略没有写,建议先看一下

Gson解析需要的jar包下载(免积分)

1.首先写Gson工具类,将Java对象转换为JSON数据,以及将JSON数据转换为Java对象

package com.zml.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

/**

  • @author zml2015

  • @Time:2016年2月2日 下午2:15:38

  • @version 1.0
    */
    public class GsonTools {

    /**TODO 转换为json字符串

    • @param src 要转换成json格式的 对象
    • @return
      */
      public static String createJsonString(Object src) {
      Gson gson = new Gson();
      String jsonString = gson.toJson(src);
      return jsonString;
      }

    /**TODO 转换为指定的 对象

    • @param jsonString
    • @param type 指定对象的类型 ,即 T.class
    • @return
      */
      public static <T> T getObject(String jsonString, Class<T> type) {
      T t = null;
      try {
      Gson gson = new Gson();
      t = gson.fromJson(jsonString, type);
      } catch (JsonSyntaxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      }
      return t;
      }

    /**得到 一个List<T>集合

    • @param jsonString
    • @param type T的类型
    • @return
      */
      public static <T> List<T> getList(String jsonString, Class<T> type) {
      List<T> list = new ArrayList<T>();
      Gson gson = new Gson();
      list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
      }.getType());
      return list;

    }

    /**TODO 得到一个List<T> 的集合

    • @param jsonString json字符串

    • @param type 数组的类型 ,即T[].class

    • @return
      */
      public static <T> List<T> StringTolist(String jsonString, Class<T[]> type) {
      T[] list = null;
      try {
      Gson gson = new Gson();
      list = gson.fromJson(jsonString, type);
      } catch (JsonSyntaxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      }

      return Arrays.asList(list);

    }
    /**把json字符串转换为 String 集合

    • @param jsonString
    • @return
      */
      public static List<String> getStrings(String jsonString) {
      List<String> list = new ArrayList<String>();
      Gson gson = new Gson();
      new TypeToken<List<String>>(){}.getType();
      list = gson.fromJson(jsonString, new TypeToken<List<String>>() {
      }.getType());
      return list;

    }

    /**TODO 将json数据解析为Map<String,Object>集合

    • @param jsonString

    • @return
      */
      public static List<Map<String, Object>> getMaps(String jsonString) {

      List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
      Gson gson = new Gson();
      list = gson.fromJson(jsonString,
      new TypeToken<List<Map<String, Object>>>() {
      }.getType());

      return list;

    }

}

2.开始测试

package com.zml.test;

import java.util.List;
import java.util.Map;

import com.zml.pojo.Person;
import com.zml.utils.DataUtil;
import com.zml.utils.GsonTools;
import com.zml.utils.JsonTools;


/**
 * @author zml2015
 * @Time:2016年2月3日 下午1:10:44
 * @version 1.0  
 */
public class testgson {

	public static void main(String[] args) {
			String jsonString;
			jsonString = GsonTools.createJsonString(DataUtil.getPerson());
			System.out.println("-------------------转化为Json字符串------------------");
			System.out.println(jsonString);			
			System.out.println("-------------------解析后------------------");
			Person person = GsonTools.getPerson(jsonString, Person.class);
			System.out.println(person.toString());
			
			System.out.println("-------------------转化为Json字符串------------------");
			jsonString = GsonTools.createJsonString(DataUtil.getPersons());
			System.out.println(jsonString);	
			System.out.println("-------------------解析后------------------");
			List<Person> list = GsonTools.getlist(jsonString, Person.class);
			System.out.println(list.toString());
			
			
			System.out.println("-------------------转化为Json字符串------------------");
			jsonString = GsonTools.createJsonString(DataUtil.getStrings());
			System.out.println(jsonString);		
			System.out.println("-------------------解析后------------------");
			List<String> list2 = GsonTools.getStrings(jsonString);
			System.out.println(list2.toString());
			
			
			System.out.println("-------------------转化为Json字符串------------------");
			jsonString = GsonTools.createJsonString(DataUtil.getMaps());
			System.out.println(jsonString);		
			System.out.println("-------------------解析后------------------");
			List<Map<String, Object>> list3 = GsonTools.getMaps(jsonString);
			System.out.println(list3.toString());
		}
		

}

 

测试截图

 

http://img.blog.csdn.net/20160203144339626

3.测试成功后,开始编写Servlet,测试

 

package com.zml.test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zml.utils.DataUtil;
import com.zml.utils.GsonTools;
import com.zml.utils.JsonTools;

/**

  • @author zml2015

  • @Time:2016年2月3日 下午1:02:56

  • @version 1.0
    */
    public class GsonServlet extends HttpServlet {

    /**

    • Constructor of the object.
      */
      public GsonServlet() {
      super();
      }

    /**

    • Destruction of the servlet. <br>
      */
      public void destroy() {
      super.destroy(); // Just puts "destroy" string in log
      // Put your code here
      }

    /**

    • 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);
    }

    /**

    • 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 {

      response.setContentType("text/html;charset=utf-8");
      PrintWriter out = response.getWriter();
      String jsonString="";
      String actionString = request.getParameter("action");

      if (actionString.equals("person")) {

       jsonString = GsonTools.createJsonString(DataUtil.getPerson());
      

      } else if (actionString.equals("persons")) {

       jsonString = GsonTools.createJsonString(DataUtil.getPersons());
      

      } else if (actionString.equals("strings")) {

       jsonString = GsonTools.createJsonString(DataUtil.getStrings());
      

      } else if (actionString.equals("maps")) {

       jsonString = GsonTools.createJsonString(DataUtil.getMaps());
      

      }
      System.out.println(jsonString);
      out.print(jsonString);
      out.flush();
      out.close();
      }

    /**

    • Initialization of the servlet. <br>
    • @throws ServletException if an error occurs
      */
      public void init() throws ServletException {
      // Put your code here
      }

}

 

测试成功截图:

 

http://img.blog.csdn.net/20160203144831307

 

http://img.blog.csdn.net/20160203144840987

 

http://img.blog.csdn.net/20160203145308973

 

源码下载(免积分)

 

 

 

 

 

 

 

 

 

 

Q.E.D.