I just started developing in Java and chose Jersey (2.4.1) as the framework I will use to build restful services.
When serializing a model, is there any annotation (moxy or jackson) to not serialize a property only if the value is default?
For example, in the case of reference types this would be null, but in the case of an int or long, the default value is 0.
Is this possible?
Just figured this out. Using Jackson, you would use the following annotation:
#JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
public class User
{
...
}
Haven't figured out MOXy yet, however.
Related
I need to (de)serialize to and from JSON some of the data classes that are generated by a Gradle plugin. Normally I would just use a library like Moshi or kotlinx.serialization and add the proper annotation to the class I want to serialize but, since this data classes are autogenerated, this is a problem.
I would like to avoid manually to map all the fields of the generated data class to some other class that I can (de)serialize, or to write a custom adapter for all these data class so, I was wondering if there is another way to tell, for example, kotlinx.serialization that a class is #Serializable without having to put the annotation directly on top of the class itself.
Or, alternatively, is there a better way to convert to and from a string an instance of a generated data class?
kotlinx.serialization supports generating serializers for 3rd party classes. We need to use forClass parameter in #Serializer, for example:
data class MyData(val data: String)
#Serializer(forClass = MyData::class)
object MyDataSerializer
fun main() {
val data = MyData("foo")
println(Json.encodeToString(MyDataSerializer, data))
}
You can read more in the official documentation: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#deriving-external-serializer-for-another-kotlin-class-experimental
I have JAXB annotated class which i am trying to convert to JSON using jackson objectMapper. The issue with generated json is jackson is introduction a new property value:"xxx" for XMLValue annotation which is dont value. for example it is generated as below
{
"employeeName":
{
"value":"ABC"
}
}
but i want it as {"employeeName":"ABC"} instead
One more thing is while it wraps the arrays i am getting as below in the generated json
{
"Employers":{
"Employer":[
{
"name":"ddd"
}
]
}
instead i want it as only
{"Employer":[{"name":"ddd"}]}
Can someone suggest if above two are possible with jackson.
Yes, this is possible. It might be helpful when you provide your class so you could get a more specific answer which might use annotations. But at least you could write a custom serializer. If you do so you have full control over the produced json.
Json.NET 6.0.1 adds F# support for records and discriminated unions. When serializing a F# record type using Json.NET I now get nicely formatted JSON.
The serialization is done as follow:
let converters = [| (new StringEnumConverter() :> JsonConverter) |]
JsonConvert.SerializeObject(questionSet, Formatting.Indented, converters)
However, when I try to expose my F# types through a ASP.NET WebApi 5.0 service, written in C#, the serialized JSON includes an #-sign infront of all properties. The #-sign comes from the internal backing field for the record type (this used to be a known problem with Json.Net and F#).
But - since I'm using the updated version of Json.NET, shouldn't the result be the same as when calling JsonConvert? Or is JsonConvert behaving differently than JsonTextWriterand JsonTextReader?
As far as I can tell from reading the JsonMediaTypeFormatter in the WebApi source JsonTextWriterand JsonTextReader is used by WebApi.
You can adorn your records with the [<CLIMutable>] attribute:
[<CLIMutable>]
type MyDtr = {
Message : string
Time : string }
That's what I do.
For nice XML formatting, you can use:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer <- true
For nice JSON formatting, you can use:
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver <-
Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
I believe it's because the backing fields that are emitted by F# records don't follow the same naming convention as C# property backing fields.
The easiest way I've found to get around this is to change the ContractResolver at the startup of your web application from the System.Net.Http.Formatting.JsonContractResolver to use the Newtonsoft.Json.Serialization.DefaultContractResolver instead: -
Formatters.JsonFormatter.SerializerSettings.ContractResolver <- DefaultContractResolver()
You'll then get all JSON formatting done via Newtonsoft's JSON formatter rather than the NET one.
I am attempting to use the ToFactory extension for Ninject, but am running into a few problems.
If I have a constructor like this:
public ListenerReader(IDepen1 depen1, IDepen2 depen2, UdpClient client, DataReceiveModes dataReceiveMode, int receivePort)
{
}
And then I create a factory to automatically create the items like this:
public interface IListenerReaderFactory
{
ListenerReader CreateListenerReader(UdpClient client, DataReceiveModes dataReceiveMode, int receivePort);
}
I receive an activation error when I try to call the injected factory:
Error activating int
No matching bindings are available, and the type is not self-bindable.
It seems like Ninject does not like to inject primitive types in the factories. I have also seen this same error but with the string type in another factory?
If this does not work do I have to separate the parameters into a called method?
EDIT:
It appears that the type in question was being injected outside of the factory. Thus Ninject was trying to create bindings for the enum and int types which failed.
The problem was the factory was not being called and the type was being injected directly instead.
In my Google Web Toolkit project, I got the following error:
com.google.gwt.user.client.rpc.SerializationException: Type ‘your.class.Type’ was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.
What are the possible causes of this error?
GWT keeps track of a set of types which can be serialized and sent to the client. your.class.Type apparently was not on this list. Lists like this are stored in .gwt.rpc files. These lists are generated, so editing these lists is probably useless. How these lists are generated is a bit unclear, but you can try the following things:
Make sure your.class.Type implements java.io.Serializable
Make sure your.class.Type has a public no-args constructor
Make sure the members of your.class.Type do the same
Check if your program does not contain collections of a non-serializable type, e.g. ArrayList<Object>. If such a collection contains your.class.Type and is serialized, this error will occur.
Make your.class.Type implement IsSerializable. This marker interface was specifically meant for classes that should be sent to the client. This didn't work for me, but my class also implemented Serializable, so maybe both interfaces don't work well together.
Another option is to create a dummy class with your.class.Type as a member, and add a method to your RPC interface that gets and returns the dummy. This forces the GWT compiler to add the dummy class and its members to the serialization whitelist.
I'll also add that if you want to use a nested class, use a static member class.
I.e.,
public class Pojo {
public static class Insider {
}
}
Nonstatic member classes get the SerializationException in GWT 2.4
I had the same issue in a RemoteService like this
public List<X> getX(...);
where X is an interface. The only implementation did conform to the rules, i.e. implements Serializable or IsSerializable, has a default constructor, and all its (non-transient and non-final) fields follow those rules as well.
But I kept getting that SerializationException until I changed the result type from List to X[], so
public X[] getX(...);
worked. Interestingly, the only argument being a List, Y being an interface, was no problem at all...
I have run into this problem, and if you per chance are using JPA or Hibernate, this can be a result of trying to return the query object and not creating a new object and copying your relavant fields into that new object. Check the following out, which I saw in a google group.
#SuppressWarnings("unchecked")
public static List<Article> getForUser(User user)
{
List<Article> articles = null;
PersistenceManager pm = PMF.get().getPersistenceManager();
try
{
Query query = pm.newQuery(Article.class);
query.setFilter("email == emailParam");
query.setOrdering("timeStamp desc");
query.declareParameters("String emailParam");
List<Article> results = (List<Article>) query.execute(user.getEmail
());
articles = new ArrayList<Article>();
for (Article a : results)
{
a.getEmail();
articles.add(a);
}
}
finally
{
pm.close();
}
return articles;
}
this helped me out a lot, hopefully it points others in the right direction.
Looks like this question is very similar to what IsSerializable or not in GWT?, see more links to related documentation there.
When your class has JDO annotations, then this fixed it for me (in addition to the points in bspoel's answer) : https://stackoverflow.com/a/4826778/1099376