0
votes

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"
1
Is the object always in this same format, or can it change dynamically?Trevor Bye
inner classes need to be static or another way for them to be instantiated , for example there is no zero-argument constructor or any annotations. cowtowncoder.com/blog/archives/2010/08/entry_411.htmlstacktraceyo
Annotate the class you're deserialising with @JsonIgnoreProperties(ignoreUnknown = true)teppic
Fix your "fourth" and "fifth" classes by making them static.Vaelyr
@J.West There is a situation that json can not have all fields I've mention above.Nubzor

1 Answers

0
votes

FYI

@JsonIgnoreProperties(ignoreUnknown = true)

has solved the issue!

Thanks.