简体   繁体   中英

Using Jackson JSON Parser: Complex JSON?

I have a complex JSON that I am trying to parse using Jackson 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:

{
    "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:

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.

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

  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.

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.

whatever your json: here is an utility which is up to transform json2object or 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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