whats the difference between responseBody and Serialization - spring-mvc

In Spring Framework,i am using responseBody annotation and serialization,i learned that responseBody is for HttpMessageConverts,it will return the output to view Resolver and serialization will convert the data in to byte stream and transfer it using version Id and header,here i have a question that, whats the difference between this two ?

Serialization is a computer science concept that describes how a data structure can be broken down and stored. Deserialization is the reverse, taking a stored format and converting it back into a data structure.
#ResponseBody is an annotation that Spring MVC uses on #RequestMapping methods. It tells the DispatcherServlet to take the return value of your handler method and, using an HttpMessageConverter, serialize it and write it directly to the HTTP response OutputStream.
See the javadoc of HttpMessageConverter for a list of implementation classes. You can write byte[], String, InputStream, Resource objects directly to the stream. There also exist HttpMessageConverter classes for converting any object returned by the handler method to JSON or XML.

Related

Consume Web Service, Serialize XML response, save xml to database

I have this situation, I am creating a Web Service in C# where I need to consume a SOAP Web Service, which gives me an XML response back, I need to serialize this XML response and save it to a table in the database.
I have tried the to call the XML in Postman and it worked fine with a
200 OK status
, but I need how to serialize this reponse and save it to the database.
And then I have tried to write this:
public void CreateFilter(Student student)
{
var XML = XmlSerialization <Student> (student);
ConnectDataBase db = new ConnectDataBase();
SqlCommand cmd = new SqlCommand("sp_Student");
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = student.name;
cmd.Parameters.Add("#surname", SqlDbType.VarChar).Value = student.surname;
cmd.Parameters.Add("#subject", SqlDbType.VarChar).Value = student.subject;
cmd.Parameters.Add("#student", SqlDbType.Xml).Value = XML;
}
Any thoughts on how to get a response from the Web Service I have to consume, and then serialize the response I'm getting back and then save the serialization on the database?
Thank you in advance
Well, you have a couple of options really. Essentially, if you aren't leveraging an ORM (like Hibernate or some such), you want to:
Grab the XML payload
Get that deserialized into an object instance so you can work with it
Pick out the data you are interested in and persist it
Step 2 is essentially writing a class (or tree of classes) that mimmicks the field structure of the XML, then asking a library nicely to parse the XML state into an instance of that class. This then makes it easy to work with for you.
You can either leverage the the native deserialization as per:
https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer.deserialize?view=net-6.0
Or, just for arguments sake alternatively you could use a modern serialization library. There isn't much of a good choice when it comes to XML and C#, so the main one I can think of that will get you from point a to point b is Json.NET:
https://www.newtonsoft.com/json
This library, though predomenantly pushed as an all-in-one object mapper for JSON is also able to translate between XML and Json:
https://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm
Depending on how much of a fight the native deserializer puts up (defining the schema can be a bit of a pain, bloody SOAP am I right), it might be easier to use Json.NET to hoover up the XML, convert it to JSON, then deserialize that json as an object.
This gives you a 2-step deserialization process which isn't ideal, but it's not such a bad thing either as you get to work with the "nice" library and not have to fight the old baked in xml serialization stuff.
The choice is yours really. I'd give the first option a good go first then if that puts up too much of a fight you have Json.NET to fall back on :)

What's the difference between serialize and encode?

I'm using Symfony\Component\Serializer\Serializer, and I'm not sure what the difference between the serialize and encode methods is. They have identical signatures, and in practice they seem to give identical output.
Based on the official docs, serializing involves two phases: normalizing and encoding. Normalizing converts input data into array, while encoding crunches that array down to desirable format (be it JSON, XML or something else).
The serialize method of the Symfony Serializer is a wrapper on its encode method. Note that you can call the encode method separately. The serialize method can call the normalize method before the encode method depending on the fact that the requested encoder (eg: json) needs normalization or not.
If you intend to do a JSON serialization, the encode method of the serializer will eventually call json_encode PHP native method. And this method performs a serialization in fact...
For example, if you look into the jsonSerialize method of the jsonSerializable native class of PHP, you can read in the description:
Serializes the object to a value that can be serialized natively by json_encode().
So, at least, in the case of the JSON format, we can say that encoding is serializing in fact but in lower level.
If you call the encode method directly without using the serialize method, you will serialize your data into the expected format but will not take benefits of the normalize process if needed.

Returning null from a spring mvc controller method

I have read the Spring documentation and I was not able to find relevant information regarding the expected behavior of a Spring MVC controller method returning null (with a return type of String).
Can someone please provide a reply or direct me to relevant documentation? Or to put it another way, what would be the benefit of returning null from a Spring MVC controller method?
In Spring 2, when you returned null from a controller you were saying to the Spring dispatcher that you don't want it to search for a view.
You did this if you were handling the response yourself by writing the response content directly and then flushing the output stream (you were managing a file download for example).
If you didn't return null, Spring would have forwarded to a view who would try to write to the response also, messing up your already written data or resulting in an exception if the response was already commited.
Returning null was a way of saying back off to Spring's view resolver.
A lot of things changed in Spring 3 and now the same can be obtained by having an #RequestMapping annotated method that returns void.
If you have a return type of String but you return null I think that it uses the default RequestToViewNameTranslator for translating an incoming HttpServletRequest into a logical view name when the view name wasn't explicitly supplied.
Return type String in spring mvc generally returns your view resolver, it can be your JSP, html or any other view page.
http://www.mkyong.com/spring3/spring-3-mvc-hello-world-example/
Suppose you want to return a normal String like "hi", you can use #ResponseBody annotation to do this.

Why the value webservice returns was not xml

webservice.PService pService = new Project.webservice.PService();
var v3 = passportService.HelloWorld();
Response.Write(v3);
I debugged it and found that v3 was string. Why? Should not a webservcie always return xml?
The webservice was:
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
Edit:
What if I want an object or a list of objects to be returned by the webservcie?
I suggest you might want to start with Microsoft.
Then have a look at returning objects.
Whilst the webservice transport layer uses XML, there's an awful lot of stuff in there that your application code typically isn't going to care about, which is why the client proxies strip it all out for you, so that you're left with the the bits that you're interested in.
As long as the object you want to return from your WebMethod is serializable, you should be able to just define it as a return type and it'll get encoded for you. When you generate the client side proxy, a similar object will be created for the request to be deserialized into.
Returning collections of objects from your WebMethod is essentially the same, although it's worth noting that List<T> is converted to an Array, over the wire.
The web service takes an object, and serialises it to XML, and sends that XML back to the client. The client/proxy parses that XML, and deserialises it back to an object. The type returned is determined by your web method signature. If you wanted to see the original XML, you could do so by inspecting the HTTP messages, but the point of using the proxy is that it does the conversion for you.

Are there options with Json.NET that can have it deserialize inconsistent json types into objects?

An example would be that I am consuming json from an api. The api is not consistent in how it returns the json. Say you have an Author and it has a property of Books[]. The api is unfortunately choosing to return Author.Books (of type Book) in cases when there is only one book. The prefered method would be to return just one Book inside Author.Books[].
Json.NET understandably throws a serialization exception when I try to have it deserialize a chunk of json and it finds "Author":{"Book":{... mixed in with "Author":{"Book":["...
Is there a way around this?
Does this answer your question?
Deserializing JSON when sometimes array and sometimes object
I guess the best would be fix the json through a regex replace before sending to the deserializer. If you put here a full sample of a json provided by the API, and a json accepted, i could make the regex for you.

Resources