This SO question explains how to ignore extra fields when deserializing JSON with Jackson
by using #JsonIgnoreProperties(ignoreUnknown=true), but I want to know when/why should I do this?
This overrides the default for Jackson, which is to throw an exception for unexpected fields. I assume if I should just use this default normally, but when/why would I want to design my system to be strict vs accept anything it can?
I guess this is more of a design philosophy question, so let me know if this is not the right place to ask.
The SO question itself has one of the scenarios as an answer to this question.
The problem is, the JSON objects might change and have new fields added while the application is published, but currently it will break even when a simple String field is added, which can safely be ignored.
There can be various scenarios where you need to ignore some of the json properties while serializing/deserializing JSON like If you are consuming json from a web service and just want few meaningful fields to be serialized. For example from an employee details json, you want just the employee first name and last name. This way you will avoid having a heavy employee object.
If the consumed service upgrades in future adding some fields, your code will continue to work.
Related
ExcludeStrategy in Gson allows you to filter fields based on reference type. But due to polymorphism, we can have an object that contains much more fields. Which basically means ExcludeStrategy is actually useless in this case. I think this was quite a bad design in Gson.
The issue is that by getting the field, you can find out what class/interface that field was declared in, but can't find out what is the actual instance that is currently processed by Gson. So you can't use ExcludeStrategy other than for pretty basic models, not for hierarchies.
Is there a way to tell Gson what fields to log and which to skip, without using annotations, at runtime?
Maybe something like SimpleBeanPropertyFilter in Jackson framework?
There isn't anything for this. I've opened an issue with a suggestion of how to get this outcome, but so far no updates:
https://github.com/google/gson/issues/1272
Follow that issue for an update. I'll also update this answer whenever there's any progress.
Recently I was involved in a discussion regarding parsing response data from a REST API.
My point was that only client necessary data should be parsed from JSON object. In my opinion there's no obvious reason to clutter a client object with information not needed for it's use case.
Other opinion stated that we should parse the response 1:1 so that it reflects received data entirely and than create some intermediate object for client usage only with the sufficient properties. In this case I don't see any obvious reason how this approach would benefit anything.
Are there any best practices regarding this topic? What are the pros/cons regarding each solution?
When you say "parsed" form a JSON object, what do you mean? JSON is an object representation... Are you making another object that looks like the JSON object for some reason but isn't the one generated by JSON.parse()?
Assuming that is what you are doing, then you should make that new object as focused as possible, perhaps as a ViewModel. There would be little point in creating ANOTHER JavaScript object that looks just like the results of JSON.parse().
If this is not what you are trying to accomplish, then I likely need more details to comment.
We're using JaxRS & Jackson to send data to our client. Since the client is Javascript, we don't really need to send null values or empty arrays if there isn't a valid value for that property (which JaxRS does by default). Is there a way around this?
An example. JaxRS sends this:
{"prop1":[],"prop2":null,"prop3":"foo"}
where we could have gotten away with
{"prop3":"foo"}
There are multiple ways to achieve this, depending; annotation #JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) is one way. Or, since you also want to drop empty Lists, arrays, change NON_NULL to NON_EMPTY.
It is also possible to configure this as the default behavior; in Jackson 1.9:
mapper.setSerializationConfig(mapper.getSerializationConfig().withSerializationInclusion(
JsonSerialize.Inclusion.NON_EMPTY));
and in Jackson 2.0, bit simpler:
mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
First of all dropping properties from your JSON could lead to errors or unclear code on the client side - the client side has to check if a given property exists before using it, if the property is missing there would be JavaScript error reported. Boring stuff.
Since HTTP communication is gzipped, the potential gains from removing properties does not seem significant (I can be wrong, obviously - I don't know your application). GET request can be effectively cached, so one more reason to avoid such optimalization.
You can customize serialization of Java objects to JSON as you need. See this question How can I customize serialization of a list of JAXB objects to JSON? for further explanation how to do this.
I have a LINQ to SQL entity that I will be serializing and returning as JSON over a webservice call.
There is one property on that entity that I would like not to be serialized. For this, there is generally the [ScriptIgnore] attribute, which works exactly the way I want if I manually add that to the designer.cs file.
Now, since the designer file is automatically generated, I would prefer not having to manually edit it, as any changes could easily be overwritten. My question is thus: is there any way to annotate the property so that it is excluded upon serialization, directly in the DBML editor?
If the answer is no; are there any solutions to this that are neater than manually setting the property to null before serializing it, or returning an anonymous type identical except for that one property? In MVC.NET, is there any way to pass parameters to the JSON() method to modify its behavior, perchance?
My apologies if this has been asked before - I'd expect it to be a common question, but I couldn't find anyone like it.
All the DBML generated classes are partial classes so that you can extend them in another file. The DBML designer will only alter classes in the Designer.cs file. Remove the property from the DBML designer and put it in a partial class in another file. You can then add whatever extra attributes you wish, and the DBML designer will leave it alone. You will have to manually manage this property and update it to match any database changes, but I think that is probably a price worth paying if it solves your problem.
If you will have no success with partial classes (which is probably the best way), then you can just serialize the date yourself. It is known that ASP.NET MVC use JavaScriptSerializer to serialize the data. The JavaScriptSerializer have simple and nice customization features like JavaScriptConverter and you can very easy convert the object in something less standard (see use Attr tags for json? for example or all other topics).
To be the most conform to the standards you can define a class derived from JsonResult (for example like here ASP.net MVC returning JSONP or http://dev.qsh.eu/Blogs/Dmitry-P/January-2010/ASP-NET-MVC-Tip--3.aspx) and save serialized data in context.HttpContext.Response directly with a Write method. Then you are absolutely free how you serialize the data to JSON.
Instead of using the partial class answer above you could try going into the DBML designer and setting the access modifier of the property from public to internal. I did this on table to table relationship properties and doing so worked for me to eliminate circular references when serializing my objects to JSON.
I'm trying to find the most efficient way to send my Linq2Sql objects to my jQuery plugins via JSON, preferably without additional code for each class.
The EntitySets are the main issue as they cause not only recursion, but when recursion is ignored (using JSON.NET's ReferenceLoopHandling feature) a silly amount of data can be retrieved, when I only really need 1 or 2 levels. This gets really bad when you're talking about Users, Roles and Permissions as you get the User's Role, the User's Permissions, the Role's Permissions, and the Role's Users all up in your JSON before it hits recursion and stops. Compare this to what I actually want, which is just the RoleId.
My initial approach was to send a "simplified" version of the object, where I reflect the entity and set any EntitySets to null, but of course in the above example Roles gets set to null and so RoleId is null. Setting only the 2nd level properties to null kind of works but there's still too much data as the EntitySets that weren't killed (the first level ones) repopulate their associated tables when the JsonSerializer does its reflection and I still get all those Permission objects that I just don't need.
I definately don't want to get into the situation of creating a lightweight version of every class and implementing "From" and "To" style methods on them, as this is a lot of work and seems wasteful.
Another option is to put a JsonIgnoreAttribute on the relevant properties, but this is going to cause a nightmare scenario whenever classes need to be re-generated.
My current favourite solution which I like and hate at the same time is to put the classes into opt-in serialization mode, but because I can't add attributes to the real properties I'd have to create JSON-only properties in a partial class. Again, this seems wasteful but I think it's the best so far.
Any suggestions gratefully received!
Have you tried to set the Serialization Mode in the dbml file?
It's a standard property under code generation and when you set it to Unidirectional it won't generate all the additional levels of your table structure. I've used this with silverlight and WCF to send data because the data contracts don't allow for additional levels to be sent (silverlight is very limited on what you can and can't do).
Hope this helps!