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.
CodePudding user response:
you can get this data as a JsonArray
CodePudding user response:
You can customize a little bit of code like it
public static void main(String[] args) throws ParseException {
String data = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JSONObject json = new JSONObject(
data);
JSONArray jasonArray = json.getJSONArray("data");
List list = new ArrayList();
int size = jasonArray.length();
int i = 0;
while (i < size) {
list.add(jasonArray.get(i));
i ;
}
System.out.println(list);
}
CodePudding user response:
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.
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
public class JsonList {
public static void main(String[] args) {
String json = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JsonElement elem = JsonParser.parseString(json);
if (elem.isJsonObject()) {
JsonObject obj = elem.getAsJsonObject();
elem = obj.get("data");
if (elem.isJsonArray()) {
JsonArray arr = elem.getAsJsonArray();
List<String> list = new ArrayList<>();
int count = arr.size();
for (int i = 0; i < count; i ) {
elem = arr.get(i);
if (elem.isJsonPrimitive()) {
String str = elem.getAsString();
list.add(str);
}
}
System.out.println(list);
}
}
}
}
Running the above code gives the following output:
[str1, str2, str3]
There are other ways to convert the JsonArray
to a List
. The above is not the only way. As I wrote earlier, peruse the API documentation and search the Internet.