简体   繁体   English

使用Jackson JSON Parser:复杂的JSON?

[英]Using Jackson JSON Parser: Complex JSON?

I have a complex JSON that I am trying to parse using Jackson JSON. 我有一个复杂的JSON,我试图使用Jackson JSON解析。 I am a little confused about how to get into the latLng object to pull out the lat,lng values. 我对如何进入latLng对象以拉出lat,lng值感到困惑。 This is part of the JSON: 这是JSON的一部分:

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

This is what I have so far in Java to pull it out: 到目前为止,这是我用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; }
    } 
}

and

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

RESOLVED This is how I solved the issue by using Tree Model for future reference: 解决了这个是我如何使用树模型以供将来参考解决这个问题:

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

If all you're really interested in in this input structure are lat and lng full mapping is probably the least adapted of the different approaches offered by Jackson, as it forces you to write classes to represent the different layers in your data. 如果你对这个输入结构真正感兴趣的是lat和lng完全映射可能是Jackson提供的不同方法中最不适应的,因为它迫使你编写类来表示数据中的不同层。

There are two alternatives offered by Jackson that will allow you to extract these fields without having to define these classes: Jackson提供了两种替代方案,允许您在不必定义这些类的情况下提取这些字段:

  1. The tree model offers a number of navigation methods to traverse the tree and extract the data you're interested in. 树模型提供了许多导航方法来遍历树并提取您感兴趣的数据。
  2. Simple data binding maps the JSON document onto a Map or a List which can then be navigated with the methods offered by these collections. 简单数据绑定将JSON文档映射到Map或List,然后可以使用这些集合提供的方法进行导航。

The Jackson documentation contains examples for both techniques, applying them in your program should not be too hard, use your debugger to investigate the data structures created by the parser to see how the document got mapped. Jackson文档包含两种技术的示例,在程序中应用它们不应该太难,使用调试器来调查解析器创建的数据结构,以查看文档是如何映射的。

whatever your json: here is an utility which is up to transform json2object or Object2json, 无论你的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