0

I am currently writing some code in a servlet that gets data from the database and returns it to the client. What I am having problems with is inserting the array of dates I have collected and adding them to my JSON object that I will return to the client.

Here is the code I'm trying but it keeps giving errors

dates = ClassdatesDAO.getdate(dates);
ArrayList<String> ClassDates = new ArrayList<String>();
ClassDates = dates.getClassdates();
response.setContentType("application/json");
JSONObject Dates = new JSONObject();
Dates.put("dates", new JSONArray(ClassDates));

In my IDE I get this error over the ClassDates in the JSONArray

The constructor JSONArray(ArrayList) is undefined

4
  • What library is your JSONArray from? Commented Mar 24, 2014 at 15:25
  • As an aside, replace the first two lines with List<String> classDates = dates.getClassdates();. There's no point creating an instance, if you re-assign the reference on the next line Commented Mar 24, 2014 at 15:29
  • new JSONArray should work, if it's the org.json version. It has a constructor for java.util.Collection, and an ArrayList is a Collection. Commented Mar 24, 2014 at 15:46
  • BTW, variable names in Java should begin with a lower-case letter. Classes should start with an Upper-Case letter. Commented Mar 24, 2014 at 15:49

2 Answers 2

1

You are passing ArrayList instance instead of an Array. So, convert the list into an array and then pass it as an argument like this

Dates.put("dates", new JSONArray(ClassDates.toArray(new String[ClassDates.size()])));

Note : json API has a method signature accepting java.util.Collection. So, you are using some other library or older version

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

Comments

0
      JSONObject Dates = new JSONObject();
      JSONArray datesJSONArray = new JSONArray();
      for (String date : ClassDates)
          datesJSONArray.put(date);
      try {
        Dates.put("dates", datesJSONArray);
      } catch (JSONException e) {
        e.printStackTrace();
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.