0

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) is used and the variable is then sent to a servlet using a form.

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.

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?

3
  • Don't write servlets by hand. Use Spring MVC or Jersey, and all this will be handled for you automatically. Commented Aug 2, 2015 at 23:45
  • @chrylis I don't think it would be more convenient to use spring mvc or jersey instead of plain old servlet api, since the json is passed through the request parameters not in the request body. Commented Aug 3, 2015 at 8:06
  • Please see this link, it may help stackoverflow.com/a/44389185/1404798 Commented Jun 6, 2017 at 11:54

2 Answers 2

1

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);

}
Sign up to request clarification or add additional context in comments.

Comments

0

Try using jackson for parsing the json string: https://github.com/FasterXML/jackson

For an example, look up: How to parse a JSON string to an array using Jackson

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.