有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Json数组作为对安卓客户端的响应

我有一个要求,json数组响应应该如下所示

[{“等级”:231,头衔:“《猎人之夜》”,{“等级”:232,头衔:“《加勒比海盗:黑珍珠的诅咒》”,{“等级”:233,头衔:“《拉甘:印度的一段时间》”,{“等级”:234,头衔:“《天空中的城堡》”,


安卓客户端收到的这个响应被相应地解析,不知何故,我无法生成正确的响应结构

我现在非常感谢你的帮助

@WebServlet("/JsonHost")
public class JsonHost extends HttpServlet {
    private static final long serialVersionUID = 1L;

    int rank;
    int title;

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

        PrintWriter out = response.getWriter();
        // get request parameters for userID and password

        String[] movie = {
                "The Shawshank Redemption",
                "The Godfather",
                "The Godfather: Part II",
                "The Dark Knight",
                "Pulp Fiction",
                "Schindler's List",
                "12 Angry Men"..............};


int offset=0;
    int limit=20;

        if (request.getParameter("offset") != null)
            offset = Integer.parseInt(request.getParameter("offset"));
        System.out.println("offset value:" + offset);


        JSONArray mJSONArray = new JSONArray(Arrays.asList(movie));

    //  System.out.println(gn.toJson(mJSONArray));

        //out.println(gn.toJson(mJSONArray));

        String m[][] = new String[20][20];

        for (int rank = 0; rank < offset + limit && rank < movie.length; rank++){
                for (int title = 0; title < offset+limit; title++) {

                    m[rank][title] = movie[title];



                //  System.out.println(m[rank][title]);
                    out.println(gn.toJson(m[rank][title]));
                }

            }


        }

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

        doGet(request, response);
    }

}

共 (1) 个答案

  1. # 1 楼答案

    这是你的任务。我希望它能帮助你

    JSONArray array=new JSONArray();
        int index=0;
        for(int i=231;i<235;i++){
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("rank", i);
            jsonObject.put("title", movie[index++]);
            array.put(jsonObject);
        }