使用Jackson JSON解析器:复杂的JSON?

7

我有一个复杂的JSON,正在尝试使用Jackson JSON解析。我有点困惑如何进入latLng对象来提取lat、lng值。这是JSON的一部分:

{
    "results": [
        {
            "locations": [
                {
                    "latLng": {
                        "lng": -76.85165,
                        "lat": 39.25108
                    },
                    "adminArea4": "Howard County",
                    "adminArea5Type": "City",
                    "adminArea4Type": "County",

这是我用Java编写的提取代码:

目前为止,这就是我使用Java的全部内容:

public class parkJSON
{
    public latLng _latLng;

    public static class latLng
    {
        private String _lat, _lng;
        public String getLat() { return _lat; }
        public String getLon() { return _lng; }
    } 
}

并且

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
parkJSON geo = mapper.readValue(parse, parkJSON.class);

System.out.println(mapper.writeValueAsString(geo));  
String lat = geo._latLng.getLat();
String lon = geo._latLng.getLon();
output = lat + "," + lon;
System.out.println("Found Coordinates: " + output);

已解决 以下是我使用树模型解决该问题的方法,供日后参考:

            ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
            mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);                 
            JsonNode rootNode = mapper.readTree(parse);
            JsonNode firstResult = rootNode.get("results").get(0);
            JsonNode location = firstResult.get("locations").get(0);
            JsonNode latLng = location.get("latLng");
            String lat = latLng.get("lat").asText();
            String lng = latLng.get("lng").asText();
            output = lat + "," + lng;
            System.out.println("Found Coordinates: " + output);
2个回答

6
如果您只对此输入结构中的经度和纬度感兴趣,那么完全映射可能是Jackson提供的不同方法中最不适合的一种,因为它强制您编写表示数据中不同层的类。
Jackson提供了两个替代方案,可以让您在不定义这些类的情况下提取这些字段:
1. 树模型 提供了许多导航方法来遍历树并提取您感兴趣的数据。 2. 简单数据绑定 将JSON文档映射到Map或List上,然后可以使用这些集合提供的方法进行导航。
Jackson文档包含了这两种技术的示例,将它们应用于您的程序应该不难,使用调试器来调查解析器创建的数据结构,以了解文档如何被映射。

ObjectMapper mapper = new ObjectMapper(); // 可重复使用,全局共享 mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode rootNode = mapper.readTree(parse); JsonNode firstResult = rootNode.get("results").get(0); JsonNode location = firstResult.get("locations").get(0); JsonNode latLng = location.get("latLng"); String lat = latLng.get("lat").asText(); String lng = latLng.get("lng").asText();
- Ronnie Dove
太好了 :-) 祝你的项目好运。 - fvu
这是我使用Jackson和树模型解析了世界天气在线JSON API的方法。mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, false); JsonNode rootNode = mapper.readTree(parseData); JsonNode firstResult = rootNode.get("data"); JsonNode currentCondition = firstResult.get("current_condition").get(0); tempC =currentCondition.get("temp_C").asText();weatherDesc = currentCondition.get("weatherDesc").get(0).get("value").asText(); - sAm

0
无论您的JSON是什么:这里有一个实用程序,可以将JSON转换为对象或对象转换为JSON。
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 
 * @author TIAGO.MEDICI
 * 
 */
public class JsonUtils {

    public static boolean isJSONValid(String jsonInString) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            mapper.readTree(jsonInString);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public static String serializeAsJsonString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objMapper = new ObjectMapper();
        objMapper.enable(SerializationFeature.INDENT_OUTPUT);
        objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        StringWriter sw = new StringWriter();
        objMapper.writeValue(sw, object);
        return sw.toString();
    }

    public static String serializeAsJsonString(Object object, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objMapper = new ObjectMapper();
        if (indent == true) {
            objMapper.enable(SerializationFeature.INDENT_OUTPUT);
            objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        }

        StringWriter stringWriter = new StringWriter();
        objMapper.writeValue(stringWriter, object);
        return stringWriter.toString();
    }

    public static <T> T jsonStringToObject(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper objMapper = new ObjectMapper();
        obj = objMapper.readValue(content, clazz);
        return obj;
    }

    @SuppressWarnings("rawtypes")
    public static <T> T jsonStringToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper mapper = new ObjectMapper();
        obj = mapper.readValue(content, new TypeReference<List>() {
        });
        return obj;
    }

    public static <T> T jsonStringToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper mapper = new ObjectMapper();
        mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
        return obj;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接