简体   繁体   English

使用JSON库将JSON解析为JavaObject

[英]Using JSON libraries for parsing JSON to JavaObject

I'm using the IntelliJ Idea and Play Framework with Java. 我正在将IntelliJ Idea and Play Framework与Java一起使用。 I send a request to the server and get a response in JSON format. 我向服务器发送请求并获得JSON格式的响应。 But the response is huge and I actually need only one line from it. 但是响应是巨大的,我实际上只需要一行。 All the others can be ignored. 所有其他的都可以忽略。 How can I use this line further in my program as a JavaObject , and how can I ignore the other lines? 如何在程序中将此行作为JavaObject进一步使用,如何忽略其他行?

For ignoring other lines, I tried something like this: 为了忽略其他行,我尝试了如下操作:

.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,true);

but it gives me an error saying: 但这给了我一个错误:

cannot find symbol symbol: DeserializationFeature 找不到符号符号:反序列化功能

As I know, I can use Jackson library in Play Framework. 据我所知,我可以在Play Framework中使用Jackson库。 I'm not sure if I used it correctly. 我不确定我是否正确使用了它。

Here is my code: 这是我的代码:

import play.libs.Json;
import org.codehaus.jackson.map.ObjectMapper;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core;
...
StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

        return ok(response.toString());
    }

Here's the response in JSON format: https://pastebin.com/kh7pGiN5 . 这是JSON格式的响应: https : //pastebin.com/kh7pGiN5

And here's the build.sbt from the Framework, as I am not sure I used the libraries correctly: 这是来自Framework的build.sbt ,因为我不确定我是否正确使用了这些库:

// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
libraryDependencies += "com.fasterxml.jackson.core" % "jackson-core" % "2.9.8"

// https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl
libraryDependencies += "org.codehaus.jackson" % "jackson-mapper-asl" % "1.9.13"

// https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl
libraryDependencies += "org.codehaus.jackson" % "jackson-core-asl" % "1.9.13"

// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations
libraryDependencies += "com.fasterxml.jackson.core" % "jackson-annotations" % "2.9.8"

// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
libraryDependencies += "com.fasterxml.jackson.core" % "jackson-databind" % "2.9.8"

First of all you should use only FasterXML dependencies. 首先,您应该只使用FasterXML依赖项。 Remove all codehaus dependencies. 删除所有codehaus依赖项。 When you read JSON and you need only one or few elements you can read JSON as JsonNode and traverse it as a tree. 当您读取JSON ,只需要一个或几个元素,就可以将JSON读取为JsonNode并将其作为树遍历。 To speed up traversing you can use paths : /response/GeoObjectCollection/featureMember to find featureMember array and /GeoObject/metaDataProperty/GeocoderMetaData/Address/Components to find Components array in each element of featureMember . 为了加快遍历速度,可以使用以下paths/response/GeoObjectCollection/featureMember来查找featureMember数组,并使用/GeoObject/metaDataProperty/GeocoderMetaData/Address/Components来查找featureMember每个元素中的Components数组。 See below app to find out all details: 请参阅以下应用程序以查找所有详细信息:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(jsonFile);
        GeoObjectWalker walker = new GeoObjectWalker(root);

        List<String> countries = Arrays.asList("Germany", "United States of America", "Austria", "Belgium");
        countries.forEach(country -> {
            final String message = "'%s' has first province: '%s'";
            System.out.println(String.format(message, country, walker.findProvinceForCountry(country).orElse("'not found'")));
        });
    }
}

class GeoObjectWalker {

    private final JsonNode root;

    public GeoObjectWalker(JsonNode root) {
        this.root = root;
    }

    public Optional<String> findProvinceForCountry(String country) {
        // find featureMember array
        JsonNode featureMembers = root.at("/response/GeoObjectCollection/featureMember");
        if (featureMembers.isMissingNode()) {
            return Optional.empty();
        }

        for (int i = 0; i < featureMembers.size(); i++) {
            JsonNode featureMember = featureMembers.get(i);
            // find Components array
            JsonNode components = featureMember.at("/GeoObject/metaDataProperty/GeocoderMetaData/Address/Components");
            if (components.isMissingNode()) {
                continue;
            }

            if (componentsArrayContains(components, "country", country)) {
                Optional<String> province = findNameForKind(components, "province");
                if (province.isPresent()) {
                    return province;
                }
            }
        }

        return Optional.empty();
    }

    private boolean componentsArrayContains(JsonNode array, String kind, String name) {
        for (int i = 0; i < array.size(); i++) {
            JsonNode node = array.get(i);
            if (node.get("kind").asText().equals(kind) && node.get("name").asText().equals(name)) {
                return true;
            }
        }

        return false;
    }

    private Optional<String> findNameForKind(JsonNode array, String kind) {
        for (int i = 0; i < array.size(); i++) {
            JsonNode node = array.get(i);
            if (node.get("kind").asText().equals(kind)) {
                return Optional.of(node.get("name").asText());
            }
        }

        return Optional.empty();
    }
}

Above code prints: 上面的代码打印:

'Germany' has first province: 'Bayern'
'United States of America' has first province: 'South Carolina'
'Austria' has first province: 'Oberösterreich'
'Belgium' has first province: 'Vlaams Brabant'

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

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