简体   繁体   中英

Jackson mapping json to objects

Lets say I have object like this

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

I am using RestTemplate class to fetch json from URL like this:

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

after that I'd like to cast the json string to an object using jackson object mapper

import com.fasterxml.jackson.databind.ObjectMapper

passing the entity class as a second parameter

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

The question is how should I write ExampleJson entity to handle a get shown json? I tried with class like this but it seems not to work.

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
  }

}

I am getting an exception like this:

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

FYI

@JsonIgnoreProperties(ignoreUnknown = true)

has solved the issue!

Thanks.

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