杰克逊将json映射到对象

时间:2016-11-22 19:41:29

标签: java spring parsing jackson resttemplate

让我说我有这样的对象

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

之后,我想使用jackson对象映射器将json字符串强制转换为对象

import com.fasterxml.jackson.databind.ObjectMapper

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

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

问题是我应该如何编写ExampleJson实体来处理get get 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"

1 个答案:

答案 0 :(得分:0)

仅供参考

@JsonIgnoreProperties(ignoreUnknown = true)

解决了这个问题!

感谢。