This example demonstrates how to convert a JSON array to a Java list and extract the value of a specific property. The JSON array contains properties with names and values. The goal is to convert this array to a list of objects and retrieve the value of the property with the name 'temperature'.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        String json = '{"properties":[{"name":"mode","value":null},{"name":"temperature","value":"47"},{"name":"windspeed","value":null},{"name":"powerstate","value":"on"}]}';
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode jsonNode = objectMapper.readTree(json);
            List<Property> properties = new ArrayList<>();
            JsonNode propertiesNode = jsonNode.get("properties");
            for (JsonNode propertyNode : propertiesNode) {
                Property property = objectMapper.treeToValue(propertyNode, Property.class);
                properties.add(property);
            }
            for (Property property : properties) {
                if ("temperature".equals(property.getName())) {
                    System.out.println(property.getValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class Property {
        private String name;
        private String value;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}

This code uses the Jackson library to read the JSON string and convert it into a JsonNode object. Then, it iterates through the properties array and converts each element to a Property object. Finally, it iterates through the list of properties and prints the value of the property with the name 'temperature'.

The output of this code is:

47
JSON Array to List and Value Extraction in Java

原文地址: https://www.cveoy.top/t/topic/oDJd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录