杰瑞科技汇

Java如何获取JSON数组?

在Java中获取JSON数组

在Java中处理JSON数组,通常可以使用以下几种库:

Java如何获取JSON数组?-图1
(图片来源网络,侵删)

使用 org.json 库

import org.json.JSONArray;
import org.json.JSONObject;
public class JsonArrayExample {
    public static void main(String[] args) {
        String jsonArrayString = "[\"apple\", \"banana\", \"orange\"]";
        // 解析JSON数组
        JSONArray jsonArray = new JSONArray(jsonArrayString);
        // 遍历数组
        for (int i = 0; i < jsonArray.length(); i++) {
            System.out.println("Item " + i + ": " + jsonArray.getString(i));
        }
        // 或者使用增强for循环
        for (Object item : jsonArray) {
            System.out.println("Item: " + item);
        }
    }
}

使用 Gson 库

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
public class GsonJsonArrayExample {
    public static void main(String[] args) {
        String jsonArrayString = "[\"apple\", \"banana\", \"orange\"]";
        Gson gson = new Gson();
        // 解析为字符串列表
        Type listType = new TypeToken<List<String>>(){}.getType();
        List<String> fruitList = gson.fromJson(jsonArrayString, listType);
        // 遍历列表
        for (String fruit : fruitList) {
            System.out.println("Fruit: " + fruit);
        }
    }
}

使用 Jackson 库

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.List;
public class JacksonJsonArrayExample {
    public static void main(String[] args) throws Exception {
        String jsonArrayString = "[\"apple\", \"banana\", \"orange\"]";
        ObjectMapper objectMapper = new ObjectMapper();
        // 解析为字符串列表
        List<String> fruitList = objectMapper.readValue(
            jsonArrayString, 
            new TypeReference<List<String>>() {}
        );
        // 遍历列表
        for (String fruit : fruitList) {
            System.out.println("Fruit: " + fruit);
        }
    }
}

处理包含对象的JSON数组

// 使用Gson处理对象数组
String jsonArrayString = "[{\"name\":\"John\",\"age\":30},{\"name\":\"Jane\",\"age\":25}]";
Gson gson = new Gson();
Type listType = new TypeToken<List<Person>>(){}.getType();
List<Person> personList = gson.fromJson(jsonArrayString, listType);
// Person类需要定义
class Person {
    private String name;
    private int age;
    // getters and setters
}

从JSON对象中获取数组

String jsonObjectString = "{\"fruits\":[\"apple\", \"banana\", \"orange\"]}";
JSONObject jsonObject = new JSONObject(jsonObjectString);
JSONArray fruitsArray = jsonObject.getJSONArray("fruits");
// 然后可以遍历fruitsArray

选择哪个库?

  • org.json: 轻量级,适合简单场景
  • Gson: Google出品,易用,支持复杂类型转换
  • Jackson: 功能强大,性能好,是企业级应用常用选择

根据你的项目需求和已有依赖选择合适的库即可。

Java如何获取JSON数组?-图2
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇