Jackson String转List

本文介绍了一种将JSON字符串转换为List<String>的方法,并通过具体示例展示了如何使用org.codehaus.jackson库实现这一过程。文中包含了异常处理及数据遍历打印的完整流程。

一、代码如下


需求是把JSON返回的字符串转成List<String>然后获取数据:

        List<String> st = new ArrayList<>();
        st.add("1");
        st.add("2");
        st.add("3");
        st.add("4");
        org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, String.class);
        String jsonString="[1,1]";
        try {
            List<String> stringList =  (List<String>)mapper.readValue(st.toString(), javaType);
            for (int i = 0; i < stringList.size(); i++) {
                System.out.println(stringList.get(i));
            }
            List<String> lst =  (List<String>)mapper.readValue(jsonString, javaType);
            for (int i = 0; i < lst.size(); i++) {
                System.out.println(lst.get(i));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


Java 中使用 Jackson 将 JSON 字符串换为对象模型,需要借助 `ObjectMapper` 类。`ObjectMapper` 是 Jackson 库的核心类,可用于 JSON 数据和 Java 对象之间的相互换[^1][^2][^3]。 以下是使用 Jackson 将 JSON 字符串换为对象模型的详细步骤和示例代码: ### 1. 添加依赖 如果使用 Maven,在 `pom.xml` 中添加以下依赖: ```xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency> ``` 如果使用 Gradle,在 `build.gradle` 中添加以下依赖: ```groovy implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' ``` ### 2. 创建 Java 对象模型 假设要将之前的天气 JSON 字符串换为对象,需要创建对应的 Java 类。 ```java import java.util.List; class WeatherInfo { private String city; private String date; private Weather weather; private List<Forecast> forecast; // Getters and Setters public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Weather getWeather() { return weather; } public void setWeather(Weather weather) { this.weather = weather; } public List<Forecast> getForecast() { return forecast; } public void setForecast(List<Forecast> forecast) { this.forecast = forecast; } } class Weather { private String condition; private Temperature temperature; private int humidity; private Wind wind; // Getters and Setters public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } public Temperature getTemperature() { return temperature; } public void setTemperature(Temperature temperature) { this.temperature = temperature; } public int getHumidity() { return humidity; } public void setHumidity(int humidity) { this.humidity = humidity; } public Wind getWind() { return wind; } public void setWind(Wind wind) { this.wind = wind; } } class Temperature { private int min; private int max; // Getters and Setters public int getMin() { return min; } public void setMin(int min) { this.min = min; } public int getMax() { return max; } public void setMax(int max) { this.max = max; } } class Wind { private int speed; private String direction; // Getters and Setters public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public String getDirection() { return direction; } public void setDirection(String direction) { this.direction = direction; } } class Forecast { private String date; private String condition; private Temperature temperature; // Getters and Setters public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } public Temperature getTemperature() { return temperature; } public void setTemperature(Temperature temperature) { this.temperature = temperature; } } ``` ### 3. 使用 `ObjectMapper` 将 JSON 字符串换为对象 ```java import com.fasterxml.jackson.databind.ObjectMapper; public class JsonToObjectExample { public static void main(String[] args) { String json = "{\"city\": \"北京\", \"date\": \"2024-10-15\", \"weather\": {\"condition\": \"晴\", \"temperature\": {\"min\": 10, \"max\": 22}, \"humidity\": 30, \"wind\": {\"speed\": 5, \"direction\": \"北风\"}}, \"forecast\": [{\"date\": \"2024-10-16\", \"condition\": \"多云\", \"temperature\": {\"min\": 11, \"max\": 23}}, {\"date\": \"2024-10-17\", \"condition\": \"小雨\", \"temperature\": {\"min\": 8, \"max\": 18}}]}"; ObjectMapper objectMapper = new ObjectMapper(); try { WeatherInfo weatherInfo = objectMapper.readValue(json, WeatherInfo.class); System.out.println("城市: " + weatherInfo.getCity()); System.out.println("日期: " + weatherInfo.getDate()); System.out.println("当天天气状况: " + weatherInfo.getWeather().getCondition()); } catch (Exception e) { e.printStackTrace(); } } } ``` ### 代码解释 - 首先,创建 `ObjectMapper` 实例,它是 Jackson 库的核心类,用于处理 JSON 数据和 Java 对象之间的换。 - 然后,调用 `readValue` 方法,传入 JSON 字符串和目标 Java 类的 `Class` 对象,将 JSON 字符串换为对应的 Java 对象。 - 最后,通过 Java 对象的 getter 方法获取所需的属性值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值