I am writing a service that uses Jersey and JAXB. My classes are annotated with #XMLRootElement, #XMLElement, etc. I have a circular dependency between two classes, so I have annotated the circular dependent property with #XMLTransient. So when I call my service I get xml as the default, which works perfectly. However, when I try using JSON, I get repeated lines like:
{"name":"dere","entries":[{"points":0,"wins":0,"losses":0,"ties":0,"leaderboard":{"name":"dere","entries":[{"points":0,"wins":0,"losses":0,"ties":0,"leaderboard":{"name":"dere","entries":[{"points":0,"wins":0,"losses":0,"ties":0,"leaderboard":{"name":"dere","entries":[{"points":0,"wins":0,"losses":0,"ties":0,"leaderboard":{"name":"dere"," ... etc.
So it seems there is a problem with circular dependencies when I am using JSON. I would like to avoid the circular dependent item from showing up in the JSON output, like it is done in XML (because of the #XMLTransient annotation).
Can anyone provide any insight on how I would be able to achieve this?
Use #JsonIgnore instead of #XmlTransient to break the circular dependency.
I had a similar problem as you and this did the trick for me.
It's probably worth checking out Kris Zyp's JSON Referencing proposal. It was invented specifically to handle multiple references and circular references in JSON data.
(Note: Despite the article title, Dojo isn't required. The original proposal was on json.com, but that site is inaccessible to me at the moment.)
How you would implement this technique in Jersey is, unfortunately, an exercise left to the reader.
Related
i'm just new to ASP.NET and other things with it.. i am using automapper in entity framework which is giving the ERROR.......
this occurs when i tried to get the desired data with JSON response...
System.Data.Entity.DynamicProxies.Account_C2A5EBE3CC4467F8B34569FAEB8687C41333F5D82DB38AC1D2E21FC5F8A47193'.]
i have tried many resources on stackoverflow and on other platforms also but there is no solid solution to this problem.
i have turned on LAZY LOADING using virtual keyword in MODELS.
i don't want to turn off lazy loading using ..
Configuration.ProxyCreationEnabled = false;
i am searching for the other solution to load all the data using the lazy loading ..
If i am going to off lazy loading then other headaches are to face on.
please help me out Seniors ...........
Two options:
Do not serialize the entire entity. Instead, convert it to a more simple class, and then serialize that object. I recommend you to use AutoMapper for object conversion.
If you use Json.Net, you can add the JsonIgnore attribute on top of the properties you want to avoid.
My recommendation is the first option. I think is a good idea to return only the objects you really need. For that purpose, you should have simple model objects and a mapper that transforms between your entities and this model classes. If, for example, all your entity objects are completely connected, there can be the case that you will serialize the entire database, which is not desirable. Try to move out the Entities from the presentation layer.
I'm designing a very simple web app with a REST web service that utilizes JPA to interact with a PostgreSQL database and runs in TomEE. My JPA entities have bidirectional mappings and I want my REST service to consume/produce those JPA entities as XML and JSON.
XML serialization works fine because I'm using the #XmlTransient annotation on one side of each bidirectional mapping in order to prevent an infinite loop during serialization.
Unfortunately, during JSON serialization I enter an infinite loop and a StackOverflowError is generated. I assumed that since TomEE uses Apache CXF that it would also use Jettison and I thought Jettison respected the #XmlTransient annotation.
However, it looks like TomEE is actually using Johnzon and that doesn't seem to respect the #XmlTransient annotation. How can I tell Johnzon to ignore certain fields? Could I somehow use the #JsonbTransient annotation from the JSON-B spec? I'd prefer not to link against Johnzon but I tried that in order to use the #JohnzonIgnore annotation without effect. Am I better off forcing TomEE to use Jettison? Any suggestions?
You can reproduce this bug for yourself because the rest-example that TomEE posted on their web site has the same issue, http://tomee.apache.org/examples-trunk/rest-example/README.html.
First you can use #javax.json.bind.annotation.JsonbVisibility to switch to fields.
Johnzon also supports cyclic references by enabling 'johnzon.deduplicateObjects'.
It basically replaces any cyclic objeccts with JsonPointers and automatically back on deserialisation.
A detailed description can be found in the JavaDocs
https://github.com/apache/johnzon/blob/master/johnzon-mapper/src/main/java/org/apache/johnzon/mapper/MapperBuilder.java#L486
Looking for some help to serialize a deep nested java objects to Json. The constraint is that I cannot add any annotations or change the current Java code. Looking for a powerful Json library which has configuration options to convert Java to Json without altering the Java Object themselves. Following would be some of the options that might be required
Specify include/exclude fields/methods. Should be able to specify this at nested levels. A is composed of B and B is composed of C. Should have ability to specify include/exclude at C.
Include/Exclude Objects at nested levels.
Rename fields from java properties while converting to Json (at nested level objects too)
Manager circular dependencies.
Was looking at Jackson and Gson for this requirements. While there are tons of options using annotations to specify serialization configs while writing new Java Pojo's, I am looking at options where I need to specify serialization properties without changing the current Java code. Jackson and Gson do seem to have options for these, but not documented in depth.
Which library is easier to configure for the above requirements? Any other powerful library other than Jackson/Gson? Any pointers to this will be of great help.
Thanks much for your time.
As to Jackson, you might consider using so-called mix-in annotations (see f.ex http://www.studytrails.com/java/json/java-jackson-mix-in-annotation.jsp) which allow you to specify mix-ins to use, without adding them directly in the legacy classes.
This would let you use annotation-based configuration, but leave actual classes untouched.
But given all of your requirements, it may perhaps be better to just use Tree Model of Jackson or GSON (get JsonNode or such), and manually handle conversions to your liking.
You may then be able to convert tree value into POJO; Jackson, for example, has method(s) for doing this (ObjectMapper.treeToValue(), .valueToTree(), .convertValue()) which allow conversions of structurally compatible representations.
I have a horribly nested Entity Framework structure. A Schedule holds multiple defaults and multiple overrides. Each default/override has a reference back the schedule and a "Type". The Type has a reference back to any defaults or overrides it belongs to. It's messy, but I think it's probably the only way I can do what's required.
This data ends up in a browser in the form of Breeze entities. Before I can process these when saving them back at the server, I have to turn them back into JSON, which unsurprisingly trips the dreaded "Uncaught TypeError: Converting circular structure to JSON".
Now there are a number of perfectly good scripts for removing these circular structures. But all of them seem to replace the circular references with some sort of placeholder so they can be re-created as objects. But of course Entity Framework doesn't recognise these, so can't work with them.
I'm at a loss as to what to do at this point. Simply removing the circular references rather than replacing them doesn't seem to help as it can result in structures shorn of important data.
I've also tried changing my EF queries to only get back specifically the data required, but it insists on giving me absolutely everything, even though Lazy Loading is set to false and I have no .Include statements in my queries. But I feel this is solving the wrong problem, since we're bound to want to deal with complex data at some point.
Is there any other way round this?
EDIT: I've solved this temporarily by investigating the object and removing the circular properties by name. But I'd still like a generic solution if at all possible.
Seems like you are after serialization mode. find out serialization mode in properties in your designer screen and set it to unidirectional. this will solve your serialization issue.
Hope that helps!!!
Not sure I understand the question. You should never experience any kind of circularity issue, regardless of the complexity of your model, with a Breeze SaveChanges call. (Breeze internally unwraps all entities and any circularities before serializing). If you are seeing something different then this would be a bug. Is this the case?
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.