JSON Objects vs Spring Model Objects - json

I am using standard Spring MVC 3x framework and have my model entities all built up with all the good relational stuff (javax.persistence API)... integrated with my DB.
As the application evolved, we needed to support JSON calls.
Given that I have various relationships mapped out in my Model Entity layer,
(classX->classY as well as classY->classX)
I am wondering what the best practice is in translating some of these model classes to appropriate JSON objects without duplicate re-referencing?
eg: Sample buggy response
{"classX":{"id":"1", "classY":{"id":"2", "classX":{"id":"1", "classY":{"id":"2"...
I am contemplating a couple of methodologies I wouldn't mind feedback on...
Keep the existing model classes and set the cross relationships to NULL before putting it into my ModelMap so there won't be some form of re-referencing (me thinks its a HACK)
{"classX":{"id":"1", "classY":{"id":"2", "classX":null}}}
Recreate JSON classes similar to the existing models without the re-referencing classes (but I think that means they will not be as reusable... since I will end up only having classX->classY and not backwards if I wished to drill the other way for a data response).
{"jsonClassX": {"id":"1", "jsonClassY":{"id":"2"}}}
Just simply construct it as standard ModelMap mappings for every controller call. As such no concept of a reusable JSON class, and is dependent on the way the controller constructs and organises the return values. This seems like the easiest, but it means no-reusable code (besides cut and paste)...
{"x":{"id":"1", "y":{"id":"2"}}} // for controller call 1
{"y":{"id":"2", "x":{"id":"1"}}} // for controller call 2
So those are the options I am juggling with at the moment, and I wouldn't mind getting some feedback and some pointers on how others have done it.

You should use Jackson to manage your json marshalling. Then you can add annotations to your model object which tell Jackson how to handle this type of relationship. http://wiki.fasterxml.com/JacksonFeatureBiDirReferences is a good reference for how to set up these relationships.

Related

How to define custom handling for a response class in Spring doc?

I've been using arrow-kt and spring together a lot lately. I've actually constructed a bridge between the two with several key features, one of which is a spring controller that returns an Either will automatically unwrap it and either handle the exception (Left) or return the result (Right). My long term goal is to publish this as a library.
My latest obstacle is Swagger, or more accurately springdoc openapi. Obviously it is seeing the Either, but i want it to show only the Right value as the success response type. While I know there are annotations where I can set the response model on each controller method individually, I'm trying to avoid this.
My real goal is to setup some global converter so that wherever Swagger sees an Either it will automatically unpack this. I'm just not super familiar with the customization API in Spring doc, and everything I Google just points me to the ApiResponse annotation solution.
How can I define default handling for this type of response?

Django - serialize complex context structure with models and data

In django view I want to be able to serialize whole context, that is usually used to send to template (typically by calling render and passing locals).
I want to experiment with SPA+API and possibilities to go forward with and I'd like to create function, that would serialize locals to json and return it as json response.
Now problem is, that locals is typically mix of lists, dists and querysets of models.
I can serialize models using django.core.serializers or using django-rest-framework. I can serialize dict with primitive types using json library, but I don't know any simple way how to do mix of those.
Ideal would be way to go through locals dictionary and replace all found models with their serialized representations and then put it all together, maybe even specify before what serializer (in sense of drf) to use for which model. But I really don't want to reinvent wheel in case it already exists.
Anoher question is - is this even a good idea to try to do this? Return json context as alternative to server side rendering? I am in prototyping stage so I am still thinking of how to move forward and any input in the area is appreciated.
I would recommand to go with DRF
ModelSerializer will return a Json encoded array of model
Serializer with DictField will return a Json encoded dict
Serializer with ListField will return a Json encoded list
You can create Serializer with field is another Serializer for nesting purpose.
https://www.django-rest-framework.org/api-guide/fields/#composite-fields
https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
For your' question is this a good idea, i would said :
If you push data to an external source (not django) it's fine
If you push data to django template it's a bad idea, you loose a lot of django power :(

angular and turning json data into real objects (and vice-versa)

To keep this simple:
I have classes defined in typescript which have methods and properties (with lots of getter/setter logic). I then retrieve json data matching such classes. I need to be able to project these json objects into my "smart" classes. I know about class transformer but I wonder if this is really go-to approach to do this kind of stuff. Furthermore, I'm planning on using ngrx, so this whole class-transformation just looks wrong (server to json, json to state, state to class? and viceversa? I just dont see a clear pattern.
Any clarity is appreciated. Thanks!
I'm doing almost exactly what you describe in a fairly large app.
I'm using class-transformer to transform the JSON from http calls to instances of the appropriate objects, and then using the resulting objects as state in a store (except that I'm using Redux instead of ngrx).
I find that it works very well.
I'm not sure exactly what you mean by "server to json, json to state, state to class? and viceversa?".
For me (using your terminology), it's server to json, json to class, class to state
(but state is just a collection of objects, i.e. class instances. I.E. state is objects).
If I need to send state back to the server, then yes, I typically pull the appropriate objects from the store, serialize them to JSON, and send them to the server. But...the Angular HttpClient does the serialization for you, so you don't typically have to write that part, unless you need some custom serialization.

Object mapper from and to json

I am developing an application system that has multiple executable applications on different platforms (java and .net).
For communication between them I am using JSON format. So I need to map object to and from json very frequently. Current solution (seems workaround) is jackson at java end and Newtonsoft.Json at .NET end. Problem is property name are not same and not all properties will be required at de-serialization end
So my questions are:
1. Is there any mapper to do this.
Currently using NewtonSoft.JSON.DatasetMapper at .Net end and
jsonanysetter annotation at java, but in this approach mapping
definition is loaded for each object as actual object mapping code
is in code. For example:
//C#
myobj.prop1 = dataSet.Tables[0].Rows[0]["propertyName1"].ToString();
// and so on.....
//Java
switch(key)
{
case "prop1":
myobj.setPropery1(value.toString());
break;
//and so on......
}
2. Object transformationRate needs to be very high as object are
sent and recieved at very high speed. say some 10k objects per second.
We used GSON in one of our project , i think this reference may help you, Apart from it ,there is a similar question may help you. another q/a in stackoverflow
You should take a look at Jackson. It's the de facto JSON library for Java and will happily handle turning objects into JSON and back again. It has many options to allow you to alter the output, and most per-object configuration is carried out using annotations so is visible in your model rather than hidden away in a separate configuration file.

Binding JSON to nested Grails Domain Objects

I'm developing a RESTful interface which is used to provide JSON data for a JavaScript application.
On the server side I use Grails 1.3.7 and use GORM Domain Objects for persistence. I implemented a custom JSON Marshaller to support marshalling the nested domain objects
Here are sample domain objects:
class SampleDomain {
static mapping = { nest2 cascade: 'all' }
String someString
SampleDomainNested nest2
}
and
class SampleDomainNested {
String someField
}
The SampleDomain resource is published under the URL /rs/sample/ so /rs/sample/1 points to the SampleDomain object with ID 1
When I render the resource using my custom json marshaller (GET on /rs/sample/1), I get the following data:
{
"someString" : "somevalue1",
"nest2" : {
"someField" : "someothervalue"
}
}
which is exactly what I want.
Now comes the problem: I try to send the same data to the resource /rs/sample/1 via PUT.
To bind the json data to the Domain Object, the controller handling the request calls def domain = SampleDomain.get(id) and domain.properties = data where data is the unmarshalled object.
The binding for the "someString" field is working just fine, but the nested object is not populated using the nested data so I get an error that the property "nest2" is null, which is not allowed.
I already tried implementing a custom PropertyEditorSupport as well as a StructuredPropertyEditor and register the editor for the class.
Strangely, the editor only gets called when I supply non-nested values. So when I send the following to the server via PUT (which doesn't make any sense ;) )
{
"someString" : "somevalue1",
"nest2" : "test"
}
at least the property editor gets called.
I looked at the code of the GrailsDataBinder. I found out that setting properties of an association seems to work by specifying the path of the association instead of providing a map, so the following works as well:
{
"someString" : "somevalue1",
"nest2.somefield" : "someothervalue"
}
but this doesn't help me since I don't want to implement a custom JavaScript to JSON object serializer.
Is it possible to use Grails data binding using nested maps? Or do I really heave to implement that by hand for each domain class?
Thanks a lot,
Martin
Since this question got upvoted several times I would like to share what I did in the end:
Since I had some more requirements to be implemented like security etc. I implemented a service layer which hides the domain objects from the controllers. I introduced a "dynamic DTO layer" which translates Domain Objects to Groovy Maps which can be serialized easily using the standard serializers and which implements the updates manually. All the semi-automatic/meta-programming/command pattern/... based solutions I tried to implement failed at some point, mostly resulting in strange GORM errors or a lot of configuration code (and a lot of frustration). The update and serialization methods for the DTOs are fairly straightforward and could be implemented very quickly. It does not introduce a lot of duplicate code as well since you have to specify how your domain objects are serialized anyway if you don't want to publish your internal domain object structure. Maybe it's not the most elegant solution but it was the only solution which really worked for me. It also allows me to implement batch updates since the update logic is not connected to the http requests any more.
However I must say that I don't think that grails is the appropriate tech stack best suited for this kind of application, since it makes your application very heavy-weight and inflexbile. My experience is that once you start doing things which are not supported by the framework by default, it starts getting messy. Furthermore, I don't like the fact that the "repository" layer in grails essentially only exists as a part of the domain objects which introduced a lot of problems and resulted in several "proxy services" emulating a repository layer. If you start building an application using a json rest interface, I would suggest to either go for a very light-weight technology like node.js or, if you want to/have to stick to a java based stack, use standard spring framework + spring mvc + spring data with a nice and clean dto layer (this is what I've migrated to and it works like a charm). You don't have to write a lot of boilerplate code and you are completely in control of what's actually happening. Furthermore you get strong typing which increases developer productivity as well as maintainability and which legitimates the additional LOCs. And of course strong typing means strong tooling!
I started writing a blog entry describing the architecture I came up with (with a sample project of course), however I don't have a lot of time right now to finish it. When it's done I'm going to link to it here for reference.
Hope this can serve as inspiration for people experiencing similar problems.
Cheers!
It requires you to provide teh class name:
{ class:"SampleDomain", someString: "abc",
nest2: { class: "SampleDomainNested", someField:"def" }
}
I know, it requires different input that the output it produces.
As I mentioned in the comment earlier, you might be better off using the gson library.
Not sure why you wrote your own json marshaller, with xstream around.
See http://x-stream.github.io/json-tutorial.html
We have been very happy with xstream for our back end (grails based) services and this way you can render marshall in xml or json, or override the default marshalling for a specific object if you like.
Jettison seems to produce a more compact less human readable JSON and you can run into some library collision stuff, but the default internal json stream renderer is decent.
If you are going to publish the service to the public, you will want to take the time to return appropriate HTTP protocol responses for errors etc... ($.02)