[英]How to deal with json string in java servlet
A variable called wrongAnswers which is an array of javascript objects is generated on the client. 客户端上生成了一个名为rongAnswers的变量,它是一个javascript对象数组。 It has the form
它具有形式
wrongAnswers = [
{"wrongAnswer": "Manzana", "wrongQuestion": "apple"},
{"wrongAnswer": "arbol", "wrongQuestion": "tree"}
]
JSON.stringify(wrongAnswers) is used and the variable is then sent to a servlet using a form. 使用JSON.stringify(wrongAnswers),然后使用表单将变量发送到Servlet。
Once it is in the servlet, i want to convert the JSON into a Java Arraylist. 一旦将其放入servlet中,我想将JSON转换为Java Arraylist。 I have a class Answer with 2 variables, wrongAnswer and wrongQuestion.
我有一个带有2个变量的类Answer,错误答案和错误问题。 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.
我想遍历JSON数组,并为每个对象在该JSON对象中创建一个值为errorAnswer和错误Question的Answer对象。 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.
每次将Answers对象添加到ArrayList中,最后,我将得到一个JSON的ArrayList对应于所有JSON值。
At the moment, I can use request.getParameter("json") which gets me a String with the JSON data. 此刻,我可以使用request.getParameter(“ json”)来获取一个带有JSON数据的String。 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数据的String转换为JsonArray或JsonObject,可以轻松地进行迭代,以获取名称的值:每个对象中的值对?
Some example code would have been nice, but there is many ways to parse and work with JSON. 一些示例代码本来不错,但是有很多解析和使用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);
}
Try using jackson
for parsing the json string: https://github.com/FasterXML/jackson 尝试使用
jackson
解析json字符串: https : //github.com/FasterXML/jackson
For an example, look up: How to parse a JSON string to an array using Jackson 例如,查找: 如何使用Jackson解析JSON字符串到数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.