0

I have a movie class That has a private List<String> reviews = new ArrayList<String>();

On the constructor I set

public Movie()
{
    this.reviews.add("");
}

When I try to add it to a JSON object as so,

JSONObject.put("reviews", this.reviews.toArray(new String[reviews.size()]));

I checked the JSON file and it return "reviews":[Ljava.lang.String;@5cad8086]

What is happening here? I want to put an Array of reviews into the field "reviews" like {"reviews" : ["somestring1", "somestring2"]}

Gavin
  • 2,784
  • 6
  • 41
  • 78

2 Answers2

0

json-simple apparently doesn't support adding array types directly to a JSONObject. When rendering the JSONObject to a String, it simply calls toString on its values (JSONObject is a HashMap).

As such, you're seeing the default String result of invoking toString on an array type. See

The most appropriate solution with json-simple is to create a JSONArray object from your List and add that

JSONArray array = new JSONArray();
array.addAll(reviews);
JSONObject.put("one", array);

assuming JSONObject is a variable that references a JSONObject object.


I'll end this with my opinion that json-simple is a terrible JSON parser/generator library. There are much better alternatives in Gson, Jackson, and even org.json.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
-1

You have to use this :

Arrays.toString(this.reviews.toArray(new String[reviews.size()]));

Rahman
  • 3,755
  • 3
  • 26
  • 43