UnrecognizedPropertyException in JSON with JERSEY - java

We get a org.codehaus.jackson.map.exc.UnrecognizedPropertyException with using Jerseys and Jackson as JSON-Mapper. We have an object with not native type as property (for example: not a String or int). When i use the annotation #JsonIgnore it's ok. But I must have the property.
Does anybody, which annotation should I use? In JAXB it's #XMLType?
We use Jersey 1.9.1 and Jackson 1.9.13.

I solved this. See my comment on the question.

Related

FlexJson and #JSON annotation - #JSON(name = "") not working

I just switched to FlexJson and I am already having a problem.
The documentation at http://flexjson.sourceforge.net/, chapter Controlling JSON naming with #JSON states :
When an object is serialized the names of the properties on JSON
objects are determined from the name of the Java property. This means
the names of the getter methods or the field names are used. However,
sometimes the JSON output doesn't match the names used by the Java
object. You can control this using the #JSON annotation. For example:
public class Species {
#JSON(jsonName = "genus")
private String type;
private String name;
#JSON(jsonName="species")
public String getName() {
return name;
}
}
Except it doesn't work. And then they say :
Defining a #JSON.jsonName is used in both serialization and
deserialization.
Now when I have a look into the javadocs at http://flexjson.sourceforge.net/javadoc/index.html, I can see there are 4 optional elements belonging to the #JSON annotation, those are
include name objectFactory transformer
None of it is jsonName, like in the example.
So how do I get this annotation to work, so I can have different java and json names?
How can I define this annotation element or make use of the predefined name
To clarify, I can annotate #JSON and autocomplete recommends #JSON(include), but then include cannot be resolved...
I am using FlexJson 2.1, and I imported flexjson.JSON;
Btw I am aware of this answer https://stackoverflow.com/a/8879616/2001247, but it's not what I want. I want to use annotations.
You need to use FlexJson 3.2
The problem is, latest jar accessible via developer site have 2.1 version number.
But java doc corresponds to version 3.2.
You can find FlexJson 3.2 jar in maven repository.

How to ignore new fields for an object model with Firebase 1.0.2

I'm using the last version at the moment of Firebase dependency, which is 1.0.2 and I'm having problems into getting my pojos parsed correctly.
The thing is, at any time the schema can changed but I don't want my app to crash with this:
D/AndroidRuntime(14097): Shutting down VM W/dalvikvm(14097):
threadid=1: thread exiting with uncaught exception (group=0x40a451f8)
E/AndroidRuntime(14097): FATAL EXCEPTION: main
E/AndroidRuntime(14097): com.firebase.client.FirebaseException: Failed
to bounce to type E/AndroidRuntime(14097): at
com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:213)
Looking into the dependency tree I get that Firebase is using Jackson mapper 1.9.7, so the annotation #JsonIgnoreProperties(ignoreUnknown = true") is not an option. Moreover, the object mapper is wrapped into this Firebase object so I can't configure the DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES property (DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES for Jackson 1.9 and before).
Is there any way to set this property, either as a class-level annotation or configuring the mapper or any other mechanism whatsoever?
The best solution would be that Firebase 1.0.3 started using Jackson 2.0, but don't know if this is something they care about right now.
Note: I've already thought about excluding the transitive Jackson 1.9.7 dependency and adding Jackson 2.0 so that I can access to this ignoreUnknown feature, but I don't think it is a viable choice since I would be changing the mayor version.
For those who have moved over to Google's official version of Firebase (As of May 29, 2016), you can use #Exclude instead of #JsonIgnore or #JsonProperty. Here is the link to their document.
Example:
public class dataPacket{
public String data;
...
#Exclude
public String getData(){return data;}
}
Update:
As others pointed, annotation #Exclude is right way to use it now. But if you use Kotlin that won't work. For Kotlin use
#Exclude #JvmField
var data: String? = nil
//or
#set:Exclude #get:Exclude
var data: String? = nil
Because annotation can be applied only for generated fields and not to properties.
Old answer:
I'm coming to Firebase from GSON were I used transient keyword. And that works with Firebase too
public transient String data;
As the accepted answer states, Firebase now uses Jackson, so you can annotate the desired methods you wish to ignore with
#JsonIgnore
Edit:
Firebase changed everything. Woot. Now use this instead:
#Exclude
Firebase 1.0.3 was released and now uses Jackson 2.2.2, so annotation #JsonIgnore is the way to go.
Edit:
as of now in 2017, Firebase doesn't use Jackson anymore. the correct annotation is #Exclude.

Jackson - Required property?

I'm using Jackson's readValue() method on an object mapper to read from a JSON file and convert it into my java object.
eg.
mapperObject.readValue( node, MyTargetClass.class )
Are there any annotations that I can set on MyTargetClass to enforce required attributes? For example, if I have a JSON object with properties ABC,DEF and GHI, and my Json is the following
{
"ABC" : "somevalue"
"DEF" : "someothervalue"
}
I want it to fail somehow, and only succeed on the readValue if it contained ABC, DEF and GHI.
You can mark a property as required with the #JsonProperty(required = true) annotation, and it will throw a JsonMappingException during deserialization if the property is missing or null.
Edit: I received a downvote for this without comment. I'd love to know why, since it does exactly the right thing.
Jackson does not include validation functionality, and this is by design (i.e. that is considered out-of-scope). But what is usually used is Bean Validation API implementation.
The nice thing about this is decoupling between data format handling, and validation logic.
This is what frameworks like DropWizard use; and it's the direction JAX-RS (like Jersey) are taking things for JAX-RS 2.0.
If you want to make sure a json field is provided, you have to use the #JsonProperty(value = "fieldName", required = true) annotation as a parameter to the constructor. But this is not enough, also the Constructor should have #JsonCreator annotation.
For example, if you have a field named 'endPoint' and you want o make sure it is provided in the JSON file, then the following code will throw an exception if it is not provided.
#JsonCreator
public QuerySettings(#JsonProperty(value = "endPoint", required = true) String endPoint) {
this.endPoint = endPoint;
}
I found this link helpful to understand the Jackson annotations. It also well explains why required=true is not enough and counter-intuitive to its name.
If you are neither satisfied with using #JsonProperty(required = true) as it works only with #JsonCreator nor with the use of bean validation then one more way of tackling it would be to catch this in your setter methods for the relevant variables.
You can simply check if the variable is null before setting it and throw an IllegalArgumentException or NullPointerException (as preferred by few people)
Note: It depends on how your POJO is defined too, so please make sure that it is going the setter method route for this solution to work.

jackson jsonnode property error

I want something like this
#Property
public JsonNode node
To be able to pass in directly from the rest api client.
This works in Jackson 1.9 (with no special serialization), but not in 2.1 for some reason. I get an error that says JsonNode can't be deserialized.
I created a class that implements the MessageBodyReader interface, but I'm not sure how to actually use it. How do I make this work?
Are there other workarounds?
Found the problem.
Turns out I was using the wrong JsonNode from org.codehaus.jackson.annotate.JsonProperty when I should be using com.fasterxml.jackson.annotate.JsonProperty

How Can I Map JSON to JAX-B Object?

I have some incoming JSON that I need to map to a JAXB object. Do I need to convert the JSON to XML and then populate the JAXB object, or can I map the JSON directly to the object? In either case, can someone tell me what is the best library for doing this?
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
Do I need to convert the JSON to XML and then populate the JAXB
object, or can I map the JSON directly to the object?
You do not need to convert the JSON to XML before you hand the input to a JAXB (JSR-222) implementation. If you are using the Jersey implementation (and probably others), you can set up your JAX-RS method like the following and JAXB will be used for both XML and JSON processing.
#GET
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Path("{id}")
public Customer read(#PathParam("id") long id) {
return entityManager.find(Customer.class, id);
}
JAX-RS implementations have a MessageBodyReader/MessageBodyWriter mechanism that allow you to override the default conversion. I am not aware of Gson having any support for JAXB annotations. Jackson is a object-to-JSON library that offers support for a subset of JAXB annotations (maybe regrettably). EclipseLink MOXy is a JAXB implementation, that has been extended to support JSON-binding. For an example of using it in a JAX-RS environment see:
http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html
gson is a flexible library that can convert JSON string to equivalent Java objects including pre-existing Java objects.
If you are using Jackson, You could look at the JacksonJAXBAnnotations here http://wiki.fasterxml.com/JacksonJAXBAnnotations
As a lightweight approach, you can use StAXON - JSON via StAX, https://github.com/beckchr/staxon/. StAXON provides support for JAXB, see https://github.com/beckchr/staxon/wiki/Using-JAXB.
With StAXON, binding a JAXB-annotated model to JSON is as simple as
JsonXMLMapper<Person> mapper = new JsonXMLMapper<Person>(Person.class);
Person person = mapper.readObject(input);
...
mapper.writeObject(output, person);
StAXON also supports JAX-RS, see https://github.com/beckchr/staxon/wiki/Using-JAX-RS.

Categories