简体   繁体   中英

Jackson with JSON: Unrecognized field, not marked as ignorable

I need to convert a certain JSON string to a Java object. I am using Jackson for JSON handling. I have no control over the input JSON (I read from a web service). This is my input JSON:

{"wrapper":[{"id":"13","name":"Fred"}]}

Here is a simplified use case:

private void tryReading() {
    String jsonStr = "{\"wrapper\"\:[{\"id\":\"13\",\"name\":\"Fred\"}]}";
    ObjectMapper mapper = new ObjectMapper();  
    Wrapper wrapper = null;
    try {
        wrapper = mapper.readValue(jsonStr , Wrapper.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("wrapper = " + wrapper);
}

My entity class is:

public Class Student { 
    private String name;
    private String id;
    //getters & setters for name & id here
}

My Wrapper class is basically a container object to get my list of students:

public Class Wrapper {
    private List<Student> students;
    //getters & setters here
}

I keep getting this error and "wrapper" returns null . I am not sure what's missing. Can someone help please?

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: 
    Unrecognized field "wrapper" (Class Wrapper), not marked as ignorable
 at [Source: java.io.StringReader@1198891; line: 1, column: 13] 
    (through reference chain: Wrapper["wrapper"])
 at org.codehaus.jackson.map.exc.UnrecognizedPropertyException
    .from(UnrecognizedPropertyException.java:53)

You can use Jackson's class-level annotation:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties

@JsonIgnoreProperties
class { ... }

It will ignore every property you haven't defined in your POJO. Very useful when you are just looking for a couple of properties in the JSON and don't want to write the whole mapping. More info at Jackson's website . If you want to ignore any non declared property, you should write:

@JsonIgnoreProperties(ignoreUnknown = true)

You can use

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

It will ignore all the properties that are not declared.

The first answer is almost correct, but what is needed is to change getter method, NOT field -- field is private (and not auto-detected); further, getters have precedence over fields if both are visible.(There are ways to make private fields visible, too, but if you want to have getter there's not much point)

So getter should either be named getWrapper() , or annotated with:

@JsonProperty("wrapper")

If you prefer getter method name as is.

using Jackson 2.6.0, this worked for me:

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

and with setting:

@JsonIgnoreProperties(ignoreUnknown = true)

it can be achieved 2 ways:

  1. Mark the POJO to ignore unknown properties

    @JsonIgnoreProperties(ignoreUnknown = true)
  2. Configure ObjectMapper that serializes/De-serializes the POJO/json as below:

     ObjectMapper mapper =new ObjectMapper(); // for Jackson version 1.X mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // for Jackson version 2.X mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

This just perfectly worked for me

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(
    DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

@JsonIgnoreProperties(ignoreUnknown = true) annotation did not.

Adding setters and getters solved the problem , what I felt is the actual issue was how to solve it but not how to suppress/ignore the error. I got the error " Unrecognized field.. not marked as ignorable.. "

Though I use the below annotation on top of the class it was not able to parse the json object and give me the input

@JsonIgnoreProperties(ignoreUnknown = true)

Then I realized that I did not add setters and getters, after adding setters and getters to the "Wrapper" and to the "Student" it worked like a charm.

This works better than All please refer to this property.

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    projectVO = objectMapper.readValue(yourjsonstring, Test.class);

If you are using Jackson 2.0

ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

According to the doc you can ignore selected fields or all uknown fields:

 // to prevent specified fields from being serialized or deserialized
 // (i.e. not include in JSON output; or being set even if they were included)
 @JsonIgnoreProperties({ "internalId", "secretKey" })

 // To ignore any unknown properties in JSON input without exception:
 @JsonIgnoreProperties(ignoreUnknown=true)

It worked for me with the following code:

ObjectMapper mapper =new ObjectMapper();    
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

I have tried the below method and it works for such JSON format reading with Jackson. Use the already suggested solution of: annotating getter with @JsonProperty("wrapper")

Your wrapper class

public Class Wrapper{ 
  private List<Student> students;
  //getters & setters here 
} 

My Suggestion of wrapper class

public Class Wrapper{ 

  private StudentHelper students; 

  //getters & setters here 
  // Annotate getter
  @JsonProperty("wrapper")
  StudentHelper getStudents() {
    return students;
  }  
} 


public class StudentHelper {

  @JsonProperty("Student")
  public List<Student> students; 

  //CTOR, getters and setters
  //NOTE: If students is private annotate getter with the annotation @JsonProperty("Student")
}

This would however give you the output of the format:

{"wrapper":{"student":[{"id":13,"name":Fred}]}}

Also for more information refer to https://github.com/FasterXML/jackson-annotations

Hope this helps

Jackson is complaining because it can't find a field in your class Wrapper that's called "wrapper". It's doing this because your JSON object has a property called "wrapper".

I think the fix is to rename your Wrapper class's field to "wrapper" instead of "students".

This solution is generic when reading json streams and need to get only some fields while fields not mapped correctly in your Domain Classes can be ignored:

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)

A detailed solution would be to use a tool such as jsonschema2pojo to autogenerate the required Domain Classes such as Student from the Schema of the json Response. You can do the latter by any online json to schema converter.

Annotate the field students as below since there is mismatch in names of json property and java property

public Class Wrapper {
    @JsonProperty("wrapper")
    private List<Student> students;
    //getters & setters here
}

As no one else has mentioned, thought I would...

Problem is your property in your JSON is called "wrapper" and your property in Wrapper.class is called "students".

So either...

  1. Correct the name of the property in either the class or JSON.
  2. Annotate your property variable as per StaxMan's comment.
  3. Annotate the setter (if you have one)

What worked for me, was to make the property public. It solved the problem for me.

Either Change

public Class Wrapper {
    private List<Student> students;
    //getters & setters here
}

to

public Class Wrapper {
    private List<Student> wrapper;
    //getters & setters here
}

---- or ----

Change your JSON string to

{"students":[{"id":"13","name":"Fred"}]}

set public your class fields not private .

public Class Student { 
    public String name;
    public String id;
    //getters & setters for name & id here
}

For my part, the only line

@JsonIgnoreProperties(ignoreUnknown = true)

didn't work too.

Just add

@JsonInclude(Include.NON_EMPTY)

Jackson 2.4.0

Your input

{"wrapper":[{"id":"13","name":"Fred"}]}

indicates that it is an Object, with a field named "wrapper", which is a Collection of Students. So my recommendation would be,

Wrapper = mapper.readValue(jsonStr , Wrapper.class);

where Wrapper is defined as

class Wrapper {
    List<Student> wrapper;
}

The new Firebase Android introduced some huge changes ; below the copy of the doc :

[ https://firebase.google.com/support/guides/firebase-android] :

Update your Java model objects

As with the 2.x SDK, Firebase Database will automatically convert Java objects that you pass to DatabaseReference.setValue() into JSON and can read JSON into Java objects using DataSnapshot.getValue() .

In the new SDK, when reading JSON into a Java object with DataSnapshot.getValue() , unknown properties in the JSON are now ignored by default so you no longer need @JsonIgnoreExtraProperties(ignoreUnknown=true) .

To exclude fields/getters when writing a Java object to JSON, the annotation is now called @Exclude instead of @JsonIgnore .

BEFORE

@JsonIgnoreExtraProperties(ignoreUnknown=true)
public class ChatMessage {
   public String name;
   public String message;
   @JsonIgnore
   public String ignoreThisField;
}

dataSnapshot.getValue(ChatMessage.class)

AFTER

public class ChatMessage {
   public String name;
   public String message;
   @Exclude
   public String ignoreThisField;
}

dataSnapshot.getValue(ChatMessage.class)

If there is an extra property in your JSON that is not in your Java class, you will see this warning in the log files:

W/ClassMapper: No setter/field for ignoreThisProperty found on class com.firebase.migrationguide.ChatMessage

You can get rid of this warning by putting an @IgnoreExtraProperties annotation on your class. If you want Firebase Database to behave as it did in the 2.x SDK and throw an exception if there are unknown properties, you can put a @ThrowOnExtraProperties annotation on your class.

One other possibility is this property in the application.properties spring.jackson.deserialization.fail-on-unknown-properties=false , which won't need any other code change in your application. And when you believe the contract is stable, you can remove this property or mark it true.

If for some reason you cannot add the @JsonIgnoreProperties annotations to your class and you are inside a web server/container such as Jetty. You can create and customize the ObjectMapper inside a custom provider

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

@Provider
public class CustomObjectMapperProvider implements ContextResolver<ObjectMapper> {

    private ObjectMapper objectMapper;

    @Override
    public ObjectMapper getContext(final Class<?> cls) {
        return getObjectMapper();
    }

    private synchronized ObjectMapper getObjectMapper() {
        if(objectMapper == null) {
            objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }
        return objectMapper;
    }
}

There is already many answer to this question. I'm adding to existing answers.

If you want to apply @JsonIgnoreProperties to all class in you application then the best way it is override Spring boot default jackson object.

In you application config file define a bean to create jackson object mapper like this.

@Bean
    public ObjectMapper getObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }

Now, you don't need to mark every class and it will ignore all unknown properties.

Thanks.

这对我来说非常有效

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

I fixed this problem by simply changing the signatures of my setter and getter methods of my POJO class. All I had to do was change the getObject method to match what the mapper was looking for. In my case I had a getImageUrl originally, but the JSON data had image_url which was throwing the mapper off. I changed both my setter and getters to getImage_url and setImage_url .

Hope this helps.

This may not be the same problem that the OP had but in case someone got here with the same mistake I had then this will help them solve their problem. I got the same error as the OP when I used an ObjectMapper from a different dependency as the JsonProperty annotation.

This works:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;

Does NOT work:

import org.codehaus.jackson.map.ObjectMapper; //org.codehaus.jackson:jackson-mapper-asl:1.8.8
import com.fasterxml.jackson.annotation.JsonProperty; //com.fasterxml.jackson.core:jackson-databind:2.2.3

Somehow after 45 posts and 10 years, no one has posted the correct answer for my case.

@Data //Lombok
public class MyClass {
    private int foo;
    private int bar;

    @JsonIgnore
    public int getFoobar() {
      return foo + bar;
    }
}

In my case, we have a method called getFoobar() , but no foobar property (because it's computed from other properties). @JsonIgnoreProperties on the class does not work.

The solution is to annotate the method with @JsonIgnore

The POJO should be defined as

Response class

public class Response {
    private List<Wrapper> wrappers;
    // getter and setter
}

Wrapper class

public class Wrapper {
    private String id;
    private String name;
    // getters and setters
}

and mapper to read value

Response response = mapper.readValue(jsonStr , Response.class);

I need to convert a certain JSON string to a Java object. I am using Jackson for JSON handling. I have no control over the input JSON (I read from a web service). This is my input JSON:

{"wrapper":[{"id":"13","name":"Fred"}]}

Here is a simplified use case:

private void tryReading() {
    String jsonStr = "{\"wrapper\"\:[{\"id\":\"13\",\"name\":\"Fred\"}]}";
    ObjectMapper mapper = new ObjectMapper();  
    Wrapper wrapper = null;
    try {
        wrapper = mapper.readValue(jsonStr , Wrapper.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("wrapper = " + wrapper);
}

My entity class is:

public Class Student { 
    private String name;
    private String id;
    //getters & setters for name & id here
}

My Wrapper class is basically a container object to get my list of students:

public Class Wrapper {
    private List<Student> students;
    //getters & setters here
}

I keep getting this error and "wrapper" returns null . I am not sure what's missing. Can someone help please?

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: 
    Unrecognized field "wrapper" (Class Wrapper), not marked as ignorable
 at [Source: java.io.StringReader@1198891; line: 1, column: 13] 
    (through reference chain: Wrapper["wrapper"])
 at org.codehaus.jackson.map.exc.UnrecognizedPropertyException
    .from(UnrecognizedPropertyException.java:53)

I need to convert a certain JSON string to a Java object. I am using Jackson for JSON handling. I have no control over the input JSON (I read from a web service). This is my input JSON:

{"wrapper":[{"id":"13","name":"Fred"}]}

Here is a simplified use case:

private void tryReading() {
    String jsonStr = "{\"wrapper\"\:[{\"id\":\"13\",\"name\":\"Fred\"}]}";
    ObjectMapper mapper = new ObjectMapper();  
    Wrapper wrapper = null;
    try {
        wrapper = mapper.readValue(jsonStr , Wrapper.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("wrapper = " + wrapper);
}

My entity class is:

public Class Student { 
    private String name;
    private String id;
    //getters & setters for name & id here
}

My Wrapper class is basically a container object to get my list of students:

public Class Wrapper {
    private List<Student> students;
    //getters & setters here
}

I keep getting this error and "wrapper" returns null . I am not sure what's missing. Can someone help please?

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: 
    Unrecognized field "wrapper" (Class Wrapper), not marked as ignorable
 at [Source: java.io.StringReader@1198891; line: 1, column: 13] 
    (through reference chain: Wrapper["wrapper"])
 at org.codehaus.jackson.map.exc.UnrecognizedPropertyException
    .from(UnrecognizedPropertyException.java:53)

I need to convert a certain JSON string to a Java object. I am using Jackson for JSON handling. I have no control over the input JSON (I read from a web service). This is my input JSON:

{"wrapper":[{"id":"13","name":"Fred"}]}

Here is a simplified use case:

private void tryReading() {
    String jsonStr = "{\"wrapper\"\:[{\"id\":\"13\",\"name\":\"Fred\"}]}";
    ObjectMapper mapper = new ObjectMapper();  
    Wrapper wrapper = null;
    try {
        wrapper = mapper.readValue(jsonStr , Wrapper.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("wrapper = " + wrapper);
}

My entity class is:

public Class Student { 
    private String name;
    private String id;
    //getters & setters for name & id here
}

My Wrapper class is basically a container object to get my list of students:

public Class Wrapper {
    private List<Student> students;
    //getters & setters here
}

I keep getting this error and "wrapper" returns null . I am not sure what's missing. Can someone help please?

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: 
    Unrecognized field "wrapper" (Class Wrapper), not marked as ignorable
 at [Source: java.io.StringReader@1198891; line: 1, column: 13] 
    (through reference chain: Wrapper["wrapper"])
 at org.codehaus.jackson.map.exc.UnrecognizedPropertyException
    .from(UnrecognizedPropertyException.java:53)

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties

When we are generating getters and setters, specially which starts with 'is' keyword, IDE generally removes the 'is'. eg

private boolean isActive;

public void setActive(boolean active) {
   isActive = active;
}

public isActive(){
   return isActive;
}

In my case, i just changed the getter and setter.

private boolean isActive;

public void setIsActive(boolean active) {
   isActive = active;
}

public getIsActive(){
   return isActive;
}

And it was able to recognize the field.

In my case it was simple: the REST-service JSON Object was updated (a property was added), but the REST-client JSON Object wasn't. As soon as i've updated JSON client object the 'Unrecognized field ...' exception has vanished.

In my case a I have to add public getters and setters to leave fields private.

ObjectMapper mapper = new ObjectMapper();
Application application = mapper.readValue(input, Application.class);

I use jackson-databind 2.10.0.pr3 .

Just in case anyone else is using force-rest-api like me, here is how I used this discussion to solve it (Kotlin):

var result = forceApi.getSObject("Account", "idhere")
result.jsonMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,  false)
val account: Account = result.`as`(Account::class.java)

It looks like force-rest-api is using an old version of jackson's.

您只需将List的字段从“ students”更改为“ wrapper”即可,只需json文件,然后映射器将对其进行查找。

Your json string is not inline with the mapped class. Change the input string

String jsonStr = "{\"students\"\:[{\"id\":\"13\",\"name\":\"Fred\"}]}";

Or change your mapped class

public class Wrapper {
    private List<Student> wrapper;
    //getters & setters here
}

In my case error came due to following reason

  • Initially it was working fine,then i renamed one variable,made the changes in code and it gave me this error.

  • Then i applied jackson ignorant property also but it did not work.

  • Finally after re defining my getters and setters methods according to name of my variable this error was resolved

So make sure to redifine getters and setters also.

Change Wrapper class to

public Class Wrapper {

          @JsonProperty("wrapper")  // add this line
          private List<Student> students;
}

What this does is to recognise the students field as wrapper key of the json object.

Also I personally prefer using Lombok Annotations for Getters and Setters as

@Getter
@Setter
public Class Wrapper {

          @JsonProperty("wrapper")  // add this line
          private List<Student> students;
}

Since I have not tested the above code with Lombok and @JsonProperty together, I'll suggest you to add the following code to Wrapper class as well to override Lombok's default getter and setter.

public List<Student> getWrapper(){
     return students;
}

public void setWrapper(List<Student> students){
     this.students = students;
}

Also check this out to deserialise lists using Jackson.

The shortest solution without setter/getter is to add @JsonProperty to a class field:

public class Wrapper {
    @JsonProperty
    private List<Student> wrapper;
}

public class Student {
    @JsonProperty
    private String name;
    @JsonProperty
    private String id;
}

Also, you called students list "wrapper" in your json, so Jackson expects a class with a field called "wrapper".

As per this documentation , you can use the Jackson2ObjectMapperBuilder to build your ObjectMapper:

@Autowired
Jackson2ObjectMapperBuilder objectBuilder;

ObjectMapper mapper = objectBuilder.build();
String json = "{\"id\": 1001}";

By default, Jackson2ObjectMapperBuilder disables the error unrecognizedpropertyexception.

Json field:

 "blog_host_url": "some.site.com"

Kotlin field

var blogHostUrl: String = "https://google.com"

In my case i needed just to use @JsonProperty annotation in my dataClass.

Example:

data class DataBlogModel(
       @JsonProperty("blog_host_url") var blogHostUrl: String = "https://google.com"
    )

Here's article: https://www.baeldung.com/jackson-name-of-property

ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);

I ran into this once when my JSON payload included a property that was not recognised by the API. The solution was to rename/remove the offending property.

I faced similar issue, only difference is i was working with YAML file instead of JSON file. So i was using YamlFactory() when creating an ObjectMapper. Also, the properties of my Java POJO were priviate. However, the solution mentioned in all these answers did not help. I mean, it stopped throwing error and started returning Java object but the properties of the java object would be null.

I just did the following: -

objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

And without the need of: -

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Now, i am able to deserialize data from Yaml file into Java object. All properties are not null now. This solution should work for JSON approach also.

Below is what I tried to suppress the unknown props which did not want to parse. Sharing Kotlin code

val myResponse = jacksonObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .readValue(serverResponse, FooResponse::class.java)

Simple solution for Java 11 and newer:

var mapper = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .disable(FAIL_ON_UNKNOWN_PROPERTIES)
        .disable(WRITE_DATES_AS_TIMESTAMPS)
        .enable(ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);

Important for ignoring is disabling 'FAIL_ON_UNKNOWN_PROPERTIES'

You need to verify all fields of the class you are parsing in, make it the same as in your original JSONObject . It helped me and in my case.

@JsonIgnoreProperties(ignoreUnknown = true) didn't help at all.

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