Convert json object to java object - java

I have a request like that:
let jsonData= {};
jsonData["className"]= className;
jsonData["models"]= arr;
let endPoint= "/classses?classAndModel=" + encodeURIComponent(JSON.stringfy(jsonData));
return $.ajax({
url: host + endPoint,
data: data,
cache: false,
contentType: false,
processData: false,
method: "POST"
});
I want to convert that json to java object.I tried this one
My rest service is:
#PostMapping(value=/classes",consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Void> addClassAndModelMapping(ClassAndModels classAndModels){
}
public class ClassAndModels {
ClassAndModelResult classAndModel;
...getter and setter...
}
public ClassAndModelResult {
String className;
List<String> models;
...getter and setters...
}
I get 400 error.If I change that line ClassAndModelResult classAndModel to String classAndResult.I get response but I want Object type.Do you have any idea?

The first part of code shows that you are sending data as a query string.
Take a look at https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html
But considering the #PostMapping, you should send that data in the request body and do something like this on the server side.
#PostMapping("/classes")
public ResponseEntity<Void> addClassAndModelMapping(#RequestBody ClassAndModels classAndModels){
//
}
As Phils says, you can add a GetMapping on your controller to see how your ClassAndModels its being serialized
Source: https://spring.io/guides/tutorials/bookmarks/
P.S. Sorry about my english, I'm not a native speaker.

Please try to add #RequestParam annotation or better use classAndModel value as RequestBody similar to the below.And also correct the spelling mistake in the javascript url.
#PostMapping(value = "/classes")
public ResponseEntity<Void> addClassAndModelMapping(#RequestBody ClassAndModels modal) {
}

Related

How to post boolean variable to server side as a field of a ModelAttribute object?

I have a Spring-framework based web application, and I post data from client side to server side as an object using ModelAttribute annotation.
I have an Entity bean that contains data (and stored to database later). One of the fields is a boolean field:
#Entity
#Table(name="PLAYER")
public class Player implements Serializable, JSONAble{
...
#Column(name="IS_HUNGARIAN")
private boolean isHungarian
...
}
I send the data to server side with an AJAX call using jQuery:
$.ajax({
type : "POST",
url : contextPath + 'saveEditedPlayer',
data: $('#editPlayerForm').serialize(),
success : function(result) {
alert('Success');
},error:function (xhr, ajaxOptions, thrownError){
}
});
In the Controller I receive the data like this:
#RequestMapping("/saveEditedPlayer")
#ResponseBody
public String saveEditedPlayer(#ModelAttribute final Player player, #RequestParam(required = false) final String tsiAlso) {
final JSONObject result = new JSONObject();
//some more source code
return result;
}
All the fields in the Player object are filled fine except the boolean field. According to this link the reason is that boolean values posted to server side as String value, and that is true. I have a workaround solution: I have a String field in the Entity bean, where I can store the boolean data as a String value ("true" or "false"), and in the field's set method I can set the real boolean field's value (thanks to Spring it's done automatically). But I don't think this is the right way to solve this problem.
Is there a way to post my boolean variable without any kind of helper variable?
Thank you for any kind of help in advance, if you need some more information, please ask me.
You need to name your stuff like this:
Player.java:
...
private boolean hungarian;
public boolean isHungarian() {...}
public void setHungarian(boolean hungarian) {...}
...
Your request variable is then hungarian

Reading ExtJS writer root property using Jersey rest web service

I have successfully implemented Jersey for simple WebService calls (queryparams and simple objects) but when I try to sync a store or save a record, jersey doesn't understand the rootProperty of the writer. It doesn't know where to start and it cannot Consume the json record ExtJS is sending. Unfortunately rootProperty is mandatory according to ExtJS when you transform the data to JSON so I can't do without it. I can obviously use Consumes(MediaType.TEXT_PLAIN) and transform the object myself but I'm trying to take advantage of Jersey's automatic object marshalling etc.
What is the general practice used to .sync store data or .save records?
EDIT: I don't think the problem is with my object's JSON. My store's proxy is configured as follows:
proxy: {
type: 'ajax',
url: 'ext/AnnouncementHelper/myFunction',
headers: {'Content-Type': 'application/json;charset=utf-8'},
reader: {
type: 'json',
rootProperty: 'data',
messageProperty: 'processMessage'
},
writer: {
type: 'json',
rootProperty: 'data',
encode: true,
writeAllFields: true
}
What this does is create a POST request with the following parameter:
data={id: 1, description: 'status 1'}
My model is configured as follows:
public class AnnouncementStatus {
private int id;
private String description;
#JsonCreator
public AnnouncementStatus() {
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
My function declaration is:
#POST
#Path("myFunction")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response myFunction(AnnouncementStatus status)
This gives me the following error in java:
org.codehaus.jackson.JsonParseException: Unexpected character ('d' (code 100)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
I'm guessing jackson doesn't like that my object is starting with the data= but I cannot avoid this since it is mandatory to have a root property when using stores and records.
I found a solution to the problem I had although not to the question at hand.
I still have no idea how to read the writer's root property using jersey but I found out I don't need to anymore since if we change our proxy's writer to have encoding: false it is not mandatory to set a rootProperty and it just sends the records as an array. This is understood by Jersey's serializer and it can decode the data into objects correctly.

Returning model object from Controller to Ajax jquery not working in Spring mvc

I am trying to return a model object from spring mvc controller back to jquery ajax method but it is returning blank as the response
jsp:
$( "#dialog-link10" ).click(function( event ) {
var appname= $("#dialog-link10").text();
alert(appname);
if(appname == 'RS Applications') {
$.ajax({
type : "GET",
url : 'abc.html',
dataType: 'JSON' ,
data:
{"id" : $("#dialog-link10").text()}
,
success : function(data) {
alert('success')
alert('data')
}
});}
controller:
#RequestMapping(method=RequestMethod.GET, value="/abc")
#ResponseBody
public Model helloWorld2( #RequestParam("id") String id, Model model) {
System.out.println("*****"+id);
List <String> list1=new ArrayList<String>();
List <String> list2=new ArrayList<String>();
System.out.println("here");
list1.add("abc");
list1.add("abc2");
list1.add("abc3");
list1.add("abc4");
model.addAttribute("list1", list1);
return model;
}
This is not generating success alert as well.
Please suggest
Your method should return directly the list, as a json, no need to put it in the model and return the model. Also check if you have an error in your callback ajax.
You are specifying dataType: 'JSON' in your ajax call, but you are not converting your response object (model) to json in your controller.
From the jQuery ajax documentation for dataType setting:
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string)
You'll probably want to reference a json serializer (unless you want to write your own) - but the important part is serializing your model to json in your response. For example (using json-io):
String jsonModel = JsonWriter.objectToJson(model);
return jsonModel;
You can then access the string array contained in your json response object in the following way:
success : function(data) {
for (i = 0; i < data.list1.length; i++){
alert(data.list1[i]);
}
}
And a fiddle example for reading json objects
I met this problem and it took me several hours to find out the problem.
Just remove "Model model" from your parameter.
Use a Map<String, String> or Map<String, Object> instead.
Try adding the produces = MediaType.APPLICATION_JSON to the RequestMapping annotation
#RequestMapping(method=RequestMethod.GET, value="/abc", produces = MediaType.APPLICATION_JSON)
Also, you may not need the Model paramater in the method.

json and Spring MVC

I have trouble with Spring MVC and json.
I use SimplecartJS to generate json data like this :
{"currency":"RUR",
"shipping":250,
"tax":0,
"taxRate":0,
"itemCount":2,
"item_name_1":"Name of product #1",
"item_quantity_1":6,
"item_price_1":159,
"item_options_1":"",
"item_name_2":"Name of product #2",
"item_quantity_2":2,
"item_price_2":159,
"item_options_2":"",
"form":{
"Fname":"UserName",
"Phone":"7123456789",
"Address":"UserAddress",
"Comment":"Comment Text"
}
}
My controller Spring
#RequestMapping(value = "/checkorder2", method = RequestMethod.POST, headers = "Accept=application/json")
public String test (#RequestBody OrderCon orderC)throws Exception{
ObjectMapper om = new ObjectMapper();
om.canSerialize(OrderCon.class);
System.out.println(om);
return test(orderC);
}
Code from client side
var url = 'http://localhost:8080/url'
jQuery.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
contentType:'application/json',
dataType: "json",
type: "POST",
url: url,
data: JSON.stringify(data),
And my question:
When I send data to controller, I have a mistake 400 Bad request. The request sent by the client was syntactically incorrect. When adding a new item field name will "item_name_2","item_name_3" etc. How I can parse this. I try parse to List, Set but it is not working. Please help.
UPD1: OrderCon.java
public class OrderCon {
private List<String> form;
private List<List<String>> json;
getters and setters...
}
There is no way you are going to be able to parse that data to a class like you have, since you need to add dynamic properties to a Java class.
You do however have two options to get the data out
First option is parse the json to a HasMap of Strings, ie. change your controller signature to
public String test (#RequestBody Map<String, String> orderC)
The other option is to use a JsonNode and deal with the data as a tree, here is an example http://wiki.fasterxml.com/JacksonTreeModel
I personally would try the latter first
You're getting 400 Bad Request because Spring is trying to map the passed JSON directly to your OrderCon class.
For this to work, the class would need to map to the keys specified in the JSON.
IE:
JSON:
{
"name" : "foo",
"phone": "111-111-1111"
}
would map to:
public class someJsonPojo(){
String name;
String phone;
//setters & getters
}
I don't think this will work well since instead of getting an array of items, you only get an item appended to the list as a new key:value. You should be able to modify the JSON so that you can map to an array of Item objects, which contain the name, quantity, price, etc.

Pass multiple JSON objects from client to server using jQuery and JAVA

I would like to ask about how to pass the multiple JSON object from Client to Server side. At first, I got the JSON object from 3rd Party API. After that, I want to pass them to Java method on the Server side. This is what I have tried but it is not success
on Client side (JSP)
function getInfo(InkBlob){
var myInkBlob = JSON.stringify(InkBlob);
jQuery.ajax({
type: 'POST',
url: '/webapp/filepicker/importAssets',
dataType: 'json',
data: {"inkBlob": myInkBlob}
});}
jQuery POST the data as
If I don't use JSON.stringify, the result will be like,
This is the method that Response for the incoming data
#RequestMapping(value = "/importAssets", method = RequestMethod.POST)
#ResponseBody
public void importAssets2(String[] inkBlob) throws Exception {
System.out.println(inkBlob); // print as [Ljava.lang.String;#56bdbbec (and another 2 similar)
System.out.println(inkBlob.length); // print as 15}
I want to use the data inside the object. For example, if I want to get the URL of the first object. I want to just inkBlob[0].URL. And the expected length of the inkBlob in this example should be 3 because only 3 object pass to the method. How can I achieve that???
Spring provides way to pass on a complete bean submitted from the form
Try using this :
Here InkBlob is a bean containing variable names and types exactly same as getting passed in post request.
#RequestMapping(value = "/importAssets", method = RequestMethod.POST)
#ResponseBody
public void importAssets2(#ModelAttribute(inkBlob) InkBlob inkBlob) throws Exception {
............Other code
}
Sample code for client
<form:hidden path="fileName" value="xxxx"/>
<input type = "hidden" name = "isWritable" value = "yyyyy"/>
<input type = "hidden" name="mimeType" value="zzzzz"/>
............
</form:form>
And on Server Side Handle it like this :
#RequestMapping(value = "/importAssets", method = RequestMethod.POST) #ResponseBody
public void importAssets2(#ModelAttribute("inkBlob") InkBlob inkBlob) throws Exception {
............Other code }
Where InkBlob should be like this :
public class InkBlob implements Serializable {
private static final long serialVersionUID = 15463435L;
String fileName;
String isWritable;
String mimeType;
......
public void setFileName(String fileName){
this.fileName = fileName;
}
.... Other Getters and settters.
}

Categories