【问题标题】:How do I ignore the root node when reading in a json rest api?读取 json rest api 时如何忽略根节点?
【发布时间】:2019-02-12 19:24:39
【问题描述】:

我正在阅读一个返回 Json 文件的 rest api。我需要忽略“结果”和“选项链”节点。我正在使用 Spring BootJackson 来处理对象的映射。

提前致谢!

对于 Json 文件click here

这是我的主要内容:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

@SpringBootApplication
public class OptionsImpliedMovementApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(OptionsImpliedMovementApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        String resourceURL = url;
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(resourceURL, HttpMethod.GET,entity, String.class);

        String rawJson = response.getBody();


        ObjectMapper mapper = new ObjectMapper();

        //need to read in json ignoring root node



    }

【问题讨论】:

  • 所以基本上你想忽略整个 JSON?
  • 没有问题,当我尝试将 JSON 对象映射到 java 对象时,它认为结果是一个数组。我只需要读入结果节点之后的信息。
  • 之后还是里面? “结果”实际上是一个数组。为什么不简单地更改您的 JSON 文档?
  • 反正我现在在健身房,等会儿我给你sn-p。
  • 是的,我想在“结果”中阅读。但是我不想更改 JSON 文档,因为每次我请求 rest api 时,我都会继续收到这种样式的 JSON 文档。所以我试图找到一种方法来只读取结果中的内容。由于“结果”是一个只有一个插入的数组,我觉得创建一个结果数组而只读取里面的内容是没有意义的。

标签: java json spring-boot jackson


【解决方案1】:

既然您已经收到 JSON 响应,那么建议使用

restTemplate.exchange(URL, HttpMethod.GET, requestEntity, MyPOJO.class);

而不是 String.class,根据您在 file.json 中附加的 JSON 响应定义您自己的 POJO。

您可以通过一种方便的方式快速轻松地针对来自 http://www.jsonschema2pojo.org/ 的 JSON 生成 POJO。

所以它应该看起来像:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"optionChain"
})
public class MyPOJO {

@JsonProperty("optionChain")
private OptionChain optionChain;
// getters and setters 
}

还有一个:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"result",
"error"
})
public class OptionChain {

@JsonProperty("result")
private List<Result> result = null;
@JsonProperty("error")
private Object error;
// getter and setters

}

还有其他类似的:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"expirationDate",
"hasMiniOptions",
"calls",
"puts"
})
public class Option {

@JsonProperty("expirationDate")
private Integer expirationDate;
@JsonProperty("hasMiniOptions")
private Boolean hasMiniOptions;
@JsonProperty("calls")
private List<Call> calls = null;
@JsonProperty("puts")
private List<Put> puts = null;

所以一旦你得到响应:

ResponseEntity<MyPOJO> response = restTemplate.exchange(resourceURL, HttpMethod.GET,entity, MyPOJO.class);

然后 response.getBody 将给出 optionChain 节点内的内容,这就是您要查找的内容。然后,您通常可以深入到您想要的任何节点,因为现在您拥有纯 Java 对象中的所有内容,您可以忽略任何您想要的或使用任何需要的。

使用 objectMapper 也可以达到同样的效果:

 ObjectMapper mapper = new ObjectMapper();
     MyPojo myPojo=  mapper.readValue(rawJson, MyPojo.class);

【讨论】:

  • 哈哈,很多都是白费!让我想起了“内存效率”的讨论,为什么要立即解组您的对象而不是首先检索字符串。建议再考虑一下!
  • 谢谢!所有这些代码实际上帮助我构建自定义方法。 jsonschema2pojo 减少了输入代码的时间。
  • 是的@LppEdd 我必须转换剩余的JSON,您的解决方案将以与此相同的方式返回。但两者都提供了一个可行的解决方案,所以谢谢你们!
  • 拥有多个类来获得一个作为输出是低效的(杰克逊在后台做了很多对象实例化)并且不需要。你周围的课程数量越少越好。集中 JSON 转换,这很重要。
【解决方案2】:

快速(高效)且工作。

final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonNode = objectMapper.readTree(rawJson);
final JsonNode result = jsonNode.get("optionChain")
                                .get("result");

final JsonNode firstResult = result.get(0);
final YourResultClass resultObject = objectMapper.treeToValue(firstResult, YourResultClass.class);

如果您需要忽略未知字段

final ObjectMapper objectMapper = 
      new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

【讨论】:

    猜你喜欢
    • 2015-07-23
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2022-01-26
    • 1970-01-01
    • 2014-09-11
    相关资源
    最近更新 更多