简体   繁体   中英

List<JSONObject> vs JSONArray

What is the difference between using List<JSONObject> and JSONArray ?

This is the sort of structure I wish to loop through : [{"key1","value1"},{"key2","value2"},{"key3","value3"}]

List<JSONObject> gives me the flexibility of looping through using for-each loop, while JSONArray will give JSONException when using getJSONObject method. Which is the better method here?

They are almost same apart from one major difference. If you look close at source code, JsonArray implements List .

So it is already a type of List

public interface JsonArray
extends JsonStructure, List<JsonValue> 

However the major difference is that, JsonArray is immutable .

https://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html

JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array.

Choose carefully if you want to have an immutable container of Json, use JsonArray.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM