如何处理Java Servlet中的json字符串 [英] How to deal with json string in java servlet

查看:595
本文介绍了如何处理Java Servlet中的json字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在客户端上生成了一个名为rongAnswers的变量,该变量是一组javascript对象. 格式为

A variable called wrongAnswers which is an array of javascript objects is generated on the client. It has the form

wrongAnswers = [
     {"wrongAnswer": "Manzana", "wrongQuestion": "apple"},
     {"wrongAnswer": "arbol", "wrongQuestion": "tree"}
]

使用

JSON.stringify(wrongAnswers),然后使用表单将变量发送到servlet.

JSON.stringify(wrongAnswers) is used and the variable is then sent to a servlet using a form.

一旦它在servlet中,我想将JSON转换为Java Arraylist. 我有一个带有2个变量的类Answer,错误答案和错误问题.我想遍历JSON数组,并为每个对象在该JSON对象中创建一个带有errorAnswer和错误Question值的Answer对象.每次将Answers对象添加到ArrayList中,这样最后,我就会得到一个JSON的对应于ArrayList of Answers的所有值.

Once it is in the servlet, i want to convert the JSON into a Java Arraylist. I have a class Answer with 2 variables, wrongAnswer and wrongQuestion. I would like to iterate through the JSON array, and for each object, create an Answer object with the value of wrongAnswer and wrongQuestion in that JSON Object. Each time, adding the Answer object to an ArrayList so in the end, i have an ArrayList of Answers corresponding to all the values from the JSON.

目前,我可以使用request.getParameter("json")来获取带有JSON数据的String.但是,我不确定如何处理此字符串. 有没有一种方法可以轻松地将包含JSON数据的String转换为JsonArray或JsonObject,可以轻松地进行迭代,以获取名称的值:每个对象中的值对?

At the moment, I can use request.getParameter("json") which gets me a String with the JSON data. However, i am not sure what to do with this String. Is there a way i can easily convert a String holding JSON data into a JsonArray or JsonObject, which i can easily iterate through, getting the value of the name: value pairs in each object?

推荐答案

某些示例代码本来不错,但是有很多解析和使用JSON的方法.

Some example code would have been nice, but there is many ways to parse and work with JSON.

您可以尝试的一种方法是:

One way you could try is:

JSONArray json = new JSONArray(jsonString);

ArrayList<String> array = new ArrayList<String>();

for(int index = 0; index < json.length(); index++) {

    JSONObject jsonObject = json.getJSONObject(index);

    String str= jsonObject.getString("wrongAnswer");

    array.add(str);

}

这篇关于如何处理Java Servlet中的json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆