Parent tag is missing from JSON - java

I have this DTO to be converted to XML/JSON and send response to client from my web service. We are using Jersey.
#XmlRootElement(name = "response")
public class Response {
#XmlValue
private String value="true";
}
It is getting properly converted to XML,
<response>true</response>
but json is missing out the parent tag,
it is outputting true instead of response:true
Is anybody having the same problem?

Values don't get modified with the parent names. One thing is metadata (tags), and other thing is data, that doesn't get modified.

It is actually because we are omitting parent tag while outputing JSON.
Just in this case omitting parent tag is causing problem as there is only one value in the object.

Related

RestTemplate Project: the DTO fields changing on their own

So I made Rest Client using Spring Boot that is consuming a Rest Web Service. I am passing the required requestbody but on printing the requestbody out it is not the same as my input.
For Example: What I entered was TransactionId then it would be changed to transactionId, AB_NAME would be changed to ab_NAME.
So all these fields get assigned null values.
The ResponseEntity being formed also does the same thing. I don't know why this is happening.
The dtos I have made are in line with the input I want to send so I don't know how they are changing on their own.
EDIT: So basically the web service dto fields are not using the Java naming convention but JSON automatically assumes them to be, had to use #JsonProperty to make sure the fields remain the same. Thanks for all of your help.
See your request body properties names and your model properties name should be the same as case. Writing here one example
DTO
publi class SomeName{
private string transactionId;
private string ab_NAME;
}
Sending body format should be
{
"transactionId":"11111",
"ab_NAME":"ABCDE"
}
Thanks.

Is there any way to create JSON object with keys as upper case?

Project: Android app using REST web service
Using:
Client - Volley
Server API - Jersey
Converter: Gson
This is my first time asking a question here, and i will provide my way of "evading" this code convention. Since i am working on a project where POJO fields are already defined as upper-case (sadly, i cant change that), i had to find a way to fix JSON string and convert it to an instance of uppercase POJO.
So basicaly its: client POJO <--> json object converted to/from gson <--> server POJO
So, lets say that i have a field in Users.class
String USERNAME;
When Jersey sends an instance of via #Produces, it follows the convention of creating JSON and sends an object
{"username": "random_name"}
When it gets converted from JSON via gson.fromJSON, an instance of a client's POJO will get null value for that field (obviously because field is in lower-case in JSONObject).
This is how i managed it by using a method that parses JSONObject and puts each key as upper-case:
public static String fixJSONObject(JSONObject obj) {
String jsonString = obj.toString();
for(int i = 0; i<obj.names().length(); i++){
try{
obj.names().getString(i).toUpperCase());
jsonString=jsonString.replace(obj.names().getString(i),
obj.names().getString(i).toUpperCase());
} catch(JSONException e) {
e.printStackTrace();
}
}
return jsonString;
}
And luckily since gson.fromJSON() requires String (not a JSONObject) as a parameter besides Class, i managed to solve the problem this way.
So, my question would be: Is there any elegant way of making JSON ignore that code convention and create a JSON object with an exact field? In this case:
{"USERNAME": "random_name"}
Jersey uses JAXB internally to marshall beans to xml/json. So you can always use #XmlElement annotation and use name attribute to set the attribute name to be used for marshalling
#XmlElement(name="USERNAME")
String USERNAME;
Just use annotation com.google.gson.annotations.SerializedName
Add in class Users.java:
#SerializedName("username")
String USERNAME;

Can I use number as property name in Jackson mapper?

I am using Spring MVC3.2 and Jackson for JSON mapping. I want to serialize and deserialize property name with just number. Here is my class:
public Usage implement Serializable {
private String imei;
#JsonIgnore
#JsonProperty("4")
private long j2j;
#JsonIgnore
#JsonProperty("8")
private long call;
//Getters and setters
}
JSON:
{"imei":"352985052917115", "4":20, "8":10}
Controller:
#ResponseBody
#RequestMapping(value="/alert")
public JsonResult<Void> handleOverUsageAlertByDevice(#RequestBody Usage usage){
//Do something
}
But when I send the JSON to the controller, 404 Bad request error happens, saying:
The request sent by the client was syntactically incorrect.
Can I use number as Json property name?
Your answer would be appreciated.
Yes, "numeric Strings" are perfectly legal JSON names, and Jackson supports them.
So problem should not be with that but something else in request handling.
Please try by setting the content type when sending the request.
The content type should be set as "application/json".

Returning an int whenusing webServiceTemplate.marshalSendAndReceive

I'm using Spring WebServiceTemplate class to to create and instantiate a request object of a JAXB generated class, call the marshallSendAndReceive method with it and then to cast the response object to an object of the JAXB generated response class.
This is working fine when returning the XML Objects of the JAXB generated response class (with Select Query) but now I want to execute a Delete query and just want to return the number of rows deleted. But I'm not sure how to achieve this!!
Do I need to convert that int return value into an XML object by using the following in the schema.xsd:
<xs:element name="DelResponse" type="xs:integer"/>
OR
Is there another way of achieving the same.
Thanks
Do I need to convert that int return value into an XML object
Yes. All web service messages are encoded as XML, so you need to find a way of representing everything in XML, even if it's just a plain integer.
If you want something simpler, then SOAP/Spring-WS/JAXB isn't really the tool for the job.

Converting #RequestBody to an object

Guys, Well I have done enough research still I can't find the solution to this.
In a nutshell, I'm simply passing url encoded form data to the Controller method and trying to convert it as a domain object which has Date and integers.
#RequestMapping(value = "/savePassport", method = RequestMethod.POST)
public #ResponseBody
AjaxResponse savePassport(#RequestBody StaffPassport passport, HttpServletResponse response) {
// Some operations.
}
The Staff Passport looks like this:
import java.sql.Date;
public class StaffPassport {
private int staffId;
private String passportNumber;
private String placeOfIssue;
private Date issueDate;
private Date expiryDate;
private String spouseName;
private String oldPassportRef;
private String visaInfo;
private String description;
//gets/sets
}
When I invoke the /savePassport, I get unsupported media exception. I guess it's related to casting.
I can't this working right. Of course I can catch individual form data using #RequestParam and manually do the casting but that's not the point of a framework isn't it?
Where am I going wrong? And you are right. I'm a beginner in Spring, but I love it.
Looks like you're using the wrong annotation. #RequestBody is for taking a request that has arbitrary content in its body,such as JSON, some application defined XML, comma separated variables.. whatever. And using a marshaller that you configure in the dispatcher servlet to turn it into objects.
If all you want to do is ask Spring to bind a plain old form post onto the backing object for you, the correct annotation to put on the method parameter is #ModelAttribute.
If you are posting a JSON Object with jQuery and you want Spring to be able to process it with #RequestBody, use JSON.stringify(....) in your data. Here an example:
var data = { "id": 3, "name": "test" }
$.post("processJsonData.html",JSON.stringify(data), function(data){
...
}
);
If you don't use the JSON.stringify() then you will submit the data as form data and Spring will tell you that you have an unsupported media type.
First of all be sure that you have
<mvc:annotation-driven />
in your Spring configuration file. This is mandatory for working with JSOn in SPring MVC.
Second, I recommend you to test wether request to the server has application/json content type. I belive Fiddler2 will help you to do so.
Third, but I'm not sure about it, Try to change Date items in your POJO from SQL type to regular java type.
UPDATE:
just looked at the Form and it seems like your "Accept" HTTP Header should be also application/json. Please test this issue with Fiddler2 as well.
I assume that you are posting JSON and want Spring to convert to StaffPassport. If you are getting an Unsupported media exception, it is because Spring could not figure out an appropriate way to perform the conversion.
For Spring to convert JSON, it needs Jackson -- make sure you have the Jackson jars in your project. If this is a Maven based project you can add the jackson-mapper-asl artifact ID to your pom.xml. This should give you the jackson-mapper and jackson-core jars.
Edit: I should mention that this applies to Spring 3 (I recently ran into this problem). I'm not sure what else is required for previous versions of Spring.
Check into HttpMessageConverter interface and its implementations. You could write your own implementation of it to convert it to the domain model you want. By the time the control gets to your method, you can access it as if your domain model object is passed.
Ok, I think I should refine my answer. I do not have direct experience of using it in a spring-mvc project but spring-integration. I am pretty sure the applicable media type (application/x-url-form-encoded) is already handled and converted to MultiMap by Spring framework; so, retrieve the values from that just like any other map with the key value being your form variable and populate your business model.
HTH.

Categories

Resources