JSON:响应返回不同类型的JSON类型

时间:2016-07-29 17:38:12

标签: java json ajax servlets gson

我面临一些棘手的问题。我在我的servlet中使用两个方法,用于以字符串的形式返回JSON(使用GSON api),然后我将其解析为JSON(jQuery)。我的第一种方法,即GetStates()正在按预期工作,但第二种方法即GetCity自动返回JSON对象。因此,当我解析它时,我得到"Unexpected token 0 "异常。

我不知道确切的解决方案,但我设法得到了我期望的结果。但我想知道我的代码在哪里做错了。我发布了我的完整代码。

    public class GetStates extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Connection con;
    private Statement stm;
    private List<DataList> dl;
    private String json;
    private ResultSet rs;
    private int id;

    //Code working getting json in string to jquery
    protected String GetState() throws SQLException
    {
        dl = null;
        json = null;
        stm = con.createStatement();
        rs = stm.executeQuery("select stateid, statename from states");
        dl = new ArrayList<DataList>();
        while(rs.next())
        {
            dl.add(new DataList(rs.getString(1), rs.getString(2)));
        }
        json = new Gson().toJson(dl);
        return json;
    }
    //code not working returning json in json object form to jquery 
    protected String GetCity() throws SQLException
    {
        dl = null;
        json = null;
        stm = con.createStatement();
        rs = stm.executeQuery("select districtid, districtName from districts where stateid = "+id);
        dl = new ArrayList<DataList>();
        while(rs.next())
        {
            dl.add(new DataList(rs.getString(1), rs.getString(2)));
        }
        json = new Gson().toJson(dl);
        return json;
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
            Class.forName("oracle.jdbc.OracleDriver");
            con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:xe", "payroll", "2611798");
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            if(request.getParameter("get_param").equals("New"))
            {
                response.getWriter().write(GetState());
            }
            else
            {
                id = Integer.parseInt(request.getParameter("stateid"));
                response.getWriter().write(GetCity());
            }

        }
        catch(ClassNotFoundException CNFE)
        {
            response.getWriter().write("CNF Error:Try After SOmeTime");
        }
        catch(SQLException SE)
        {
            response.getWriter().write(SE.getMessage());            
        }
    }
}


class DataList
{
    private String id;
    private String Name;
    public DataList(String id, String Name)
    {
        this.id = id;
        this.Name = Name;
    }
    public String toString() {
        return "id : " +id+ " stateName : " +Name;
//      return "{ \"id\" : \"" +id+ "\", \"stateName\" : \"" +StateName+"\"            }";
    }
}

Jquery代码

<script type="text/javascript">
$(document).ready(function(){
    $.ajax({
        type     : 'get',
        url      : 'GetStates',
        data     : {get_param:'New'},
        dataType : 'html',
        success  : function(responseText)
        {           
            $('#ajaxGetUserServletResponse').text(responseText);
            $.each(JSON.parse(responseText),function(index,element)
            {
                $('#state').append($('<option>',{value:element.id,text:element.Name}));
            });
        }
    });
});
</script>

问题在于:代码

<script type="text/javascript">
$(document).ready(function(){
    $('#state').change(function(){
        $.ajax({
            url        : 'GetStates',
            data       : {get_param : $('#state').find(":selected").val()},
            datatype   : 'html',
            success    : function(CityData)
            {
                $('#ajaxGetUserServletResponse').text(CityData);
                $.each(JSON.parse(CityData),function(index,element){
                    $('#city').append($('<option>',{value:element.id,text:element.Name}));
                });
            }
        });
    });
});
</script>

我使用Json.stringyfy获得了解决方案,并将其类型更改为JSON,但我希望使用HTML。

我只是想知道我的错误在哪里。

0 个答案:

没有答案