Is it a good practice to add redundant #JsonProperty when using JacksonMapper - json

Is it a good practice to add redundant #JsonProperty when using JacksonMapper? Even if the class vars are same named as the incoming json(and you deserialize the json)?
What can be possible upsides?
What can be possible downsides?

The downside,as you suggested, it's reduandant,especially when this class was replaced from codehaus package to fasterxml so if you have old property you will have to refactor class
org.codehaus.jackson is an older version of Jackson.
com.fasterxml.jackson represents the new project and package.

Related

SpringBoot RestController not recognizing spring.jackson.property-naming-strategy property

I have a SpringBoot (2.5.x) RestController which is returning Lists and would like to force the JSON representation to use specific naming convention for the properties. I've tried the spring.jackson.property-naming-strategy property in application.properties but it seems to have no effect. Also tried custom MappingJackson2HttpMessageConverter, using setPropertyNamingStrategy on the Autowired objectMapper, and using the #JsonNaming annotation in the controller class.
Any ideas on what I'm doing wrong?
Thanks!
--john
Put this on the class
#JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
But it is outdated
At the same time it is still available
I don't know why
my spring boot 2.5.4
This is what I ended up doing:
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonInclude.Include
import com.fasterxml.jackson.databind.PropertyNamingStrategies
import com.fasterxml.jackson.databind.annotation.JsonNaming
#JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
#JsonInclude(Include.NON_NULL)
class Facility {
String facility
String facilityCode
Integer sampleCount
}

Is there a way to use Jackson's SerializationFeature with annotations

I'm trying to use SerializationConfig.Feature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS but I'm not configuring the mapper myself, relying on annotations exclusively and letting Spring's RestTemplate (de)serialize automatically. Is there a way to enable the aforementioned feature in this scenario (i.e. annotations only)?
NOTE: I'm using Jackson 1.x and can't upgrade due to other libs...
With JAX-RS (like DropWizard) you can actually annotated resource endpoints, using #JacksonFeatures
public class Resource {
#Path("item")
#GET
#JacksonFeatures(serializationEnable={ SerializationFeature.WRAP_ROOT_VALUE })
public Pojo getItem(String id) {
...
}
}
I don't know if Spring exposes similar functionality, but it seems possible it does. And if not, it is something they should be able to add to allow per-endpoint setting/clearing of SerializationFeatures / DeserializationFeatures. So if it is not available, maybe file a feature request for Spring project?
Yes, it is possible.
checkout this link: http://jackson.codehaus.org/1.7.0/javadoc/org/codehaus/jackson/map/annotate/JsonSerialize.html
Example:
#JsonSerialize(using=MySerializer.class,
as=MySubClass.class,
include=JsonSerialize.Inclusion.NON_NULL,
typing=JsonSerialize.Typing.STATIC
)

Seam 2.3 RESTEasy on JBoss 7.1 #JsonIgnore

How to achieve that some properties are ignored in the JSON-output (like XmlTransient for XML-output)?
#GET
#Path("/{companyId}")
#Produces(MediaType.APPLICATION_JSON)
public PortfolioCompany getCompany(#PathParam("companyId") long id);
I've been playing around with the RESTeasy-support in Seam 2.3 deployed as an EAR on a JBoss 7.1. I started by adding the same dependencies to my ejb-project as in the Seam-restbay-example.
It is basically working fine for #Produces(MediaType.APPLICATION_XML), where all properties annotated with #XmlTransient are ignored, in order to prevent some LazyInitialisationExceptions.
But how to achieve this behavior for #Produces(MediaType.APPLICATION_JSON)?
I've read Seam uses Jettison by default, which uses the #XmlTransient annotation for both, XML and JSON (because technically it transforms from XML -> to JSON). But I get a "Caused by: org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer" which indicates that in fact it is using Jackson..?
For Jackson there is the annotation like #JsonIgnore, but having the same maven dependencies like restbay - this "cannot to be resolved to a type".
/**
* #return the contact
*/
#OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
#XmlTransient // working for produces XML but not for JSON
//#JsonIgnore = unknown type
public Contact getContact() {
return contact;
}
Anyone any experiences or hints on that?
thanks
EDIT: Really no one having the need of realizing lazy collections for REST-services with Seam??
After some research:
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property ="#id")
is what apparently would be needed. But that is only provided with Jackson 2.x. But the seam2.3/jboss7 setup is obviously using Jackson 1.9...
The default annotation mode of #XmlType/#XmlRootElement is to capture everyfield, including the lazy initializer from hibernate. Use #XmlAccessorType(XmlAccessType.NONE) in your entities and then individually annotate the fiels with #XmlElement so that only the necessary fields are processeded

Restlet/Jackson JSON wrapper for ArrayList<Profile>

i'm using the Restlet library for a WS server and i've recently switched from XStream/Jettison to Jackson as a JSON serializer/deserializer because of some issues.
A first drawback is that my ArrayList< Profile > (previously a Vector with Jettison) it doesn't wrap the list of Profiles when serialized and the JSON instead of "Profile:[{firstProfile}, {secondProfile}]" it looks like: [{firstProfile}, {secondProfile}]
I can overcome to this issue in the client telling manually which is the correct mapping but i would prefer to use a KVC approach.
I've looked around and it seems that it's a known issue: http://wiki.fasterxml.com/JacksonPolymorphicDeserialization (5.1 Missing type information on Serialization) that it suggest to:
Use arrays instead of Lists
Sub-class list, using class MyPojoList extends ArrayList { }
Force use of specific root type
the simplest way it should be to return an "Profile[] profile" array but it seems not working, before trying the other solutions i've rechecked around and it seems that you can use a #XmlRootElement(name = "Profile") to wrap the JSON root element: http://jira.codehaus.org/browse/JACKSON-163?focusedCommentId=213588&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-213588
so for using JAXB annotations with Jackson you need to configure the objectMapper: http://wiki.fasterxml.com/JacksonJAXBAnnotations
but in restlet to do so you need to override createObjectMapper to pass a Custom converter (see: http://restlet-discuss.1400322.n2.nabble.com/Set-custom-objectMapper-to-Jackson-Extension-td6287812.html and http://restlet-discuss.1400322.n2.nabble.com/Jackson-Mix-in-Annotations-td6211060.html#a6231831)
this is what i'm trying now! the question is there a more straightforward way to achieve this??
Thanks!!
the solution for me is to annotate the Profile class with:
#JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_OBJECT)
public class Profile extends Element implements Serializable {
and now the json now looks like:
{"Profile":{ ... }}
and the return type is a Sub-classed list:
public class ProfileList extends ArrayList<Profile>
{}
see http://wiki.fasterxml.com/JacksonPolymorphicDeserialization 5.1
I think what you want is not really available in a sense that JAX-B seems to have some rules on how to deal with lists. See this converstation on the RESTeasy mailing list

Use of metadatatype in linq-to-sql

I had asked this question
Adding more attributes to LINQ to SQL entity
Now, when I add Browsable attribute to generated entity in designer,it works.But,when I use the MetaDataType approach,and add Browsable attribute in partial class,it does not work
"I added a MetaDataType class, and added browsable attribute to property,but seems to have no effect"
Adding the MetadataTypeAttribute will only be useful when you have written custom code that detects the BrowsableAttribute. The .NET framework doesn't handle MetadataTypeAttribute any differently than any other attribute and doesn't 'merge' your type with the meta data type.
When you have written your own code that detects the BrowsableAttribute, you can change it, so it also detects a MetadataTypeAttribute on a type and if it exists, you can go to the referred metadata class to search for properties decorated with the BrowsableAttribute. When the logic using the BrowsableAttribute has not been written by you (for instance, this is part of the .NET framework, because it is used by the Visual Studio designer), there is no way of getting this to work.
Currently there are only a few parts of the .NET framework that know about the MetadataTypeAttribute. MVC for instance uses it for validation and with .NET 4.0 DataAnnotations (that defines the attribute) also has a validator. Enterprise Library 5.0 (currently in beta) will also detect this attribute for validation.
While more and more applications and part of the framework might be able to handle this attribute, in most situations using it is useless.
I'm using it so that I can allow my Linq-To-SQL classes to also have Json properties to ease deserialization of Json objects:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(User_JsonProperties))]
public partial class User
{}
public class User_JsonProperties
{
[JsonProperty("user_id")]
public int UserId { get; set; }
}
Since the other author didn't include source code, I thought I would so that you'd see what it looks like.