ChatGPT解决这个技术问题 Extra ChatGPT

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)
I found this useful to avoid creating a wrapper class: Map dummy<String,Student> = myClientResponse.getEntity(new GenericType<Map<String, Student>>(){}); and then Student myStudent = dummy.get("wrapper");
JSON should looks like: String jsonStr = "{\"students\"\:[{\"id\":\"13\",\"name\":\"Fred\"}]}"; if you are expecting Wrapper object in your REST POST request
Related (but different) question: Ignoring new fields on JSON objects using Jackson
And incidentally, most answers to this question actually answer a different question, namely one similar to the one I linke above.
majority of answers help brush problem under rug rather than actually solving it :(

T
Thomas Decaux

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)

Ariel, is there any way to declare this external to the class?
I'm serializing classes that I do not own (cannot modify). In one view, I'd like to serialize with a certain set of fields. In another view, I want a different set of fields serialized (or perhaps rename the properties in the JSON).
i must add that you do need the (ignoreUnknown = true) when annotating your class otherwise it won't work
Julián, this is not the correct answer to the question of the OP. However, I suspect that people come here because they google how to ignore properties not defined in POJO and this is the first result, so they end up up-voting this and Suresh's response (thats what happened to me). Although the original question has nothing to do with wanting to ignore undefined properties.
this is a very stupid default setting imho, if you add a property to your api, the whole serialization fails
S
Suresh

You can use

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

It will ignore all the properties that are not declared.


This didn't work for me, it still fails on unknown properties
Could u please paste atleast a piece of code what exactly u are doing, You might have missed something there..Either by doing this or by using "@JsonIgnoreProperties(ignoreUnknown = true) " Your problem should be resolved. Anyways good luck.
FWIW -- I had to import this slightly different enum: org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES
^Above is for Jackson versions prior to 2
You can also chain these calls like: getObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
N
Nomade

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.


Please elaborate - which getter needs to be changed or annotated?
you mean annotated with @JsonGetter("wrapper"), right?
@pedrambashiri No, I mean @JsonProperty. While @JsonGetter is a legal alias, it is rarely used as @JsonProperty works for getters, setters and fields; setters and getters can be distinguished by signature (one takes no arguments, returns non-void; other takes one argument).
This is the answer I was looking for! Sounds like Jackson has trouble mapping the source JSON to your POJO, but you can guarantee matches by tagging the getters. Thanks!
r
richardaum

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)

With that config annotation is unnecessary
Do you need to configure both ObjectMapper and Annotation on class? I guess objectMapper will fix for all, without a need to annotate each class. I use the annotation though.
You do not need both settings in the same class. You might also use DI to get a global singleton instance of the ObjectMapper, to set the FAIL_ON_UNKNOWN_PROPERTIES property globally.
You don't need both, you can choose one or the other.
b
bdkosher

it can be achieved 2 ways:

Mark the POJO to ignore unknown properties @JsonIgnoreProperties(ignoreUnknown = true) 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)


Why should this be the accepted answer? This just tells to ignore unknown properties, whereas the question was to find a way to get the json wrapped into an object which this solution clearly says to ignore.
Nice answer by simply using the first option.
d
ddc

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 appears to be the only answer that actually answers the question. All the other answers are just marking unknown properties as ignored, but 'wrapper' is not an unknown property, it is what we are trying to parse.
J
JJD

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.


Downvoted as it does not answer the OP's question. Ignoring unknown properties doesn't solve his problem, but leaves him with a Wrapper instance where the students list is null or empty.
2
2 revs, 2 users 70%

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

Yeah, this is the one that solved my issue - which matched the title of this post.
Answers work well for me and it's very easy.Thank you
after this my projectVO data is null.yourjsonstring having value but projectVO fields are null. Any help guys ?
this really works and the POJO also doesnt need any modifications!
A
Aalkhodiry

If you are using Jackson 2.0

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

why this config has no effect for me?
@zhaozhi It depends on Jackson version
t
tomrozb

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)

A
Alexander

It worked for me with the following code:

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

N
Nimantha

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


Welcome to stackoverflow. Tip, you can use the {} symbols in the tool bar to format your code snippets.
J
Jim Ferrans

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".


Thanks Jim. I tried that and it did not fix the problem. I am wondering if I am missing some annotation..
Hmm, what happens when you create the equivalent data in Java and then use Jackson to write it out in JSON. Any difference between that JSON and the JSON above should be a clue to what's going wrong.
This answer worked for me, with the example from the question.
N
Nimantha

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.


Why not just create a static method that does the same? What is the significance of creating a bean?
G
George Papatheodorou

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.


R
RamenChef

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
}

N
Nimantha

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

So either...

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


B
BlueRaja - Danny Pflughoeft

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


What you should actually do here is ask the specific question for the issue you have had and then answer your own question with your solution. What you have added here is not a solution to what the original question asks. You will help a lot more people if you pose your specific issue as a question.
@DRaehal The primary purpose of Stackoverflow is not (just) to answer single-use questions, but to be a repository of useful questions and answers for future googlers. This is the first result on Google, hence the various answers.
Jeff Atwood would disagree with you. stackoverflow.blog/2011/07/01/….
Upvoted because this helped me out as well. After mucking around with @JsonIgnoreProperties and adding dummy members, I found this and it did exactly what I needed. Thanks.
N
Nimantha

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.


you are right apparently: if the name you want is xxx_yyy The way to call it would be getXxx_yyy and setXxx_yyy. This is very strange but it works.
s
sagar

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

k
krmanish007

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.


c
cwa

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

thanks! import com.fasterxml.jackson.annotation.JsonProperty worked for me instead the other:-)
omfg this was killing me! ty
This!! Wasted 1 hr trying to figure out what was wrong.
N
Nimantha

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


It helps! Also class is better to do public.
j
jodu

For my part, the only line

@JsonIgnoreProperties(ignoreUnknown = true)

didn't work too.

Just add

@JsonInclude(Include.NON_EMPTY)

Jackson 2.4.0


R
Ran0990BK

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;
}

S
STaefi

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.


n
neverwinter

set public your class fields not private.

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

poor practice - this breaks the encapsulation.
I've heard that.
Your class is in risk when user uses it because the internal state could be mutated through these fields.
m
matias.g.rodriguez

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;
    }
}

N
Niamath

This worked perfectly for me

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

M
Matt S.

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

Almost. Not wrappers, but wrapper.
@Frans Haha, thank you for catching the error. I naturally use plural for a collection. But per OP's question, it should be singular.