当先锋百科网

首页 1 2 3 4 5 6 7
在Java中,将一个json格式的字符串转换为一个java类的对象。看到网上很多方法,觉得使用google的Gson的最好用。

下面一个servlet的httpRequset的处理举例:



package com.xiyou.webService;

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

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

import com.xiyou.util.FormatDateTime;

import com.google.gson.Gson;

class TransactionResponse {
    String action, loginAccount, createdInfoDetail, positionInfo;
}

public class UserAccountServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public UserAccountServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        UserAccountController userAccountController = new UserAccountController();
        String result = "";

        String jsonString =
                "{'action':'add','loginAccount':'137665123333','createdInfoDetail':'createdInfoDetail','positionInfo':'abeddafdafdadafafdfdasfadf'}";

        try {
            jsonString = request.getParameter("json");

            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");

            PrintWriter out = response.getWriter();

            Gson gson = new Gson();
            TransactionResponse tResponse = gson.fromJson(jsonString, TransactionResponse.class);
            result = tResponse.action;
            out.println(result);

            result = tResponse.loginAccount;
            out.println(result);

            result = tResponse.createdInfoDetail;
            out.println(result);

            result = tResponse.positionInfo;
            out.println(result);

            out.flush();
            out.close();

        } catch (Exception e) {
            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
            out.println("但愿朝阳常照我土,莫忘烈士鲜血满地 " + "@" + FormatDateTime.toLocalLongDateByNow());

            out.flush();
            out.close();
            e.printStackTrace();

        }

    }// json get the end of json

}