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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15035855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:18:13  来源:igfitidea点击:

Using Hymanson JSON Parser: Complex JSON?

javajsonHymanson

提问by Ronnie Dove

I have a complex JSON that I am trying to parse using Hymanson JSON. I am a little confused about how to get into the latLng object to pull out the lat,lng values. This is part of the JSON:

我有一个复杂的 JSON,我正在尝试使用 Hymanson JSON 解析它。我对如何进入 latLng 对象以提取 lat,lng 值感到有些困惑。这是 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);

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

采纳答案by fvu

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 Hymanson, as it forces you to write classes to represent the different layers in your data.

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

There are two alternatives offered by Hymanson that will allow you to extract these fields without having to define these classes:

Hymanson 提供了两种替代方案,允许您提取这些字段而无需定义这些类:

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

The Hymanson 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.

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

回答by Tiago Medici

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.Hymanson.core.JsonGenerationException;
import com.fasterxml.Hymanson.core.JsonParseException;
import com.fasterxml.Hymanson.core.type.TypeReference;
import com.fasterxml.Hymanson.databind.DeserializationFeature;
import com.fasterxml.Hymanson.databind.JsonMappingException;
import com.fasterxml.Hymanson.databind.ObjectMapper;
import com.fasterxml.Hymanson.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;
    }