I have a following JSON:
{"data":["str1", "str2", "str3"]}
I want to get a List
, i.e. ["str1", "str2", "str3"]
My code is:
JSONObject json = new JSONObject();
List list = new ArrayList();
...
// adding data in json
...
list = (List) json.get("data");
This is not working.
4
Answers
you can get this data as a JsonArray
You can customize a little bit of code like it
You wish to parse a JSON string using Java code. It is recommended to use a JSON library for Java. There are several. The below code uses Gson. There are many online examples such as Convert String to JsonObject with Gson. You should also familiarize yourself with the Gson API.
Running the above code gives the following output:
There are other ways to convert the
JsonArray
to aList
. The above is not the only way. As I wrote earlier, peruse the API documentation and search the Internet.Behind the scenes, the
JSONArray
object stores the json data in anArrayList<Object>
, and it has a method calledtoList()
. There’s absolutely no need to loop through theJSONArray
in order to set values in the array. The simpler code would look something like thisNote: This will create a list of generic Objects. The currently accepted answer doesn’t define a type for the List, which is unsafe. It doesn’t enforce type safety, and errors will occur at runtime instead of at compile time.
If you want to convert all of the inner objects to a String, you can do this by upcasting the List to an Object, and then casting it to a
List<String>
. I don’t particularly recommend it, but it can be done like this.List<String> list = (List<String>) (Object) json.getJSONArray("data").toList();
.A better way of casting the value to a specific type would be via a stream to call the
Object.toString()
method.or, if you have a specific type you want to cast it to, you can use
Finally, as others have pointed out, there are better libraries for dealing with json. Gson is a great library, however I personally prefer Jackson. They both offer similar resources, but I’ve found that Jackson’s
ObjectMapper
is more customizable and more widely used.