在Java中解析JSON字符串数组通常有以下几种方法:
1. 使用官方的`org.json`库:
```java
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonArrayExample {
public static void main(String[] args) {
String jsonArrayStr = "[{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}, {\"name\":\"Jane\", \"age\":28, \"city\":\"Los Angeles\"}]";
JSONArray jsonArray = new JSONArray(jsonArrayStr);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println("Name: " + jsonObject.getString("name"));
System.out.println("Age: " + jsonObject.getInt("age"));
System.out.println("City: " + jsonObject.getString("city"));
}
}
}
2. 使用Gson库:
```java
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
public class GsonExample {
public static void main(String[] args) {
String jsonArrayStr = "[{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}, {\"name\":\"Jane\", \"age\":28, \"city\":\"Los Angeles\"}]";
Gson gson = new Gson();
Type listType = new TypeToken
>(){}.getType();
List
persons = gson.fromJson(jsonArrayStr, listType); for (Person person : persons) {
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("City: " + person.getCity());
}
}
}
3. 使用Fastjson库:
```java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import java.util.List;
public class FastjsonExample {
public static void main(String[] args) {
String jsonArrayStr = "[{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}, {\"name\":\"Jane\", \"age\":28, \"city\":\"Los Angeles\"}]";
JSONArray jsonArray = JSON.parseArray(jsonArrayStr);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println("Name: " + jsonObject.getString("name"));
System.out.println("Age: " + jsonObject.getInteger("age"));
System.out.println("City: " + jsonObject.getString("city"));
}
}
}
以上示例展示了如何使用不同的库解析JSON字符串数组。请根据您的项目需求选择合适的库。