繁体   English   中英

使用Jackson JSON Parser:复杂的JSON?

[英]Using Jackson JSON Parser: Complex JSON?

我有一个复杂的JSON,我试图使用Jackson JSON解析。 我对如何进入latLng对象以拉出lat,lng值感到困惑。 这是JSON的一部分:

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

到目前为止,这是我用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);

如果你对这个输入结构真正感兴趣的是lat和lng完全映射可能是Jackson提供的不同方法中最不适应的,因为它迫使你编写类来表示数据中的不同层。

Jackson提供了两种替代方案,允许您在不必定义这些类的情况下提取这些字段:

  1. 树模型提供了许多导航方法来遍历树并提取您感兴趣的数据。
  2. 简单数据绑定将JSON文档映射到Map或List,然后可以使用这些集合提供的方法进行导航。

Jackson文档包含两种技术的示例,在程序中应用它们不应该太难,使用调试器来调查解析器创建的数据结构,以查看文档是如何映射的。

无论你的json是什么:这是一个实用程序,它可以转换为json2object或Object2json,

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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM