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?

javawocky
  • 899
  • 2
  • 9
  • 31
rurounisuikoden
  • 269
  • 1
  • 4
  • 16

2 Answers2

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

}
javawocky
  • 899
  • 2
  • 9
  • 31
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

Community
  • 1
  • 1
Maksim Solovjov
  • 3,147
  • 18
  • 28