繁体   English   中英

杰克逊将json映射到对象

[英]Jackson mapping json to objects

可以说我有这样的对象

{
  first: "value",
  second: "value",
  third: {
    first: "first value third",
    second: "second value third",
    fourth: {
      first: "second nested object",
      second: "second nested object"
    },
    fifth: {
      first: "another second nested object",
      second: "another second nested object"
    }
  },
  sixth: {
    first: "value",
    second: "value"
  }
}

我正在使用RestTemplate类从URL中获取json,如下所示:

RestTemplate rest = new RestTemplate();
String result = rest.getForObject(ENDPOINT_URL, String.class);

之后,我想使用杰克逊对象映射器将json字符串转换为对象

import com.fasterxml.jackson.databind.ObjectMapper

将实体类作为第二个参数传递

ObjectMapper mapper = new ObjectMapper();
object = mapper.readValue(result, ExampleJson.class);

问题是我应该如何编写ExampleJson实体来处理显示的json? 我尝试过这样的课程,但似乎没有用。

public class ExampleJson {
  private String first;

  private String second;

  private Third third;

  private Sixth sixth;

  // Getters && Setters 

  public static class Third {
    private String first;

    private String second;

    private Fourth fourth

    private Fifth fifth

    // Getters && Setters 

    private Fourth {
      private String first;

      private String second;

      // Getters && Setters
    }

    private Fifth {
      private String first;

      private String second;

      // Getters && Setters
    }
  }

  public static class Sixth {
    private String first;

    private String second;

    // Getters && Setters
  }

}

我收到这样的异常:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "fourth"

费耶

@JsonIgnoreProperties(ignoreUnknown = true)

解决了这个问题!

谢谢。

暂无
暂无

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

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