JSON parameter in spring MVC controller
This could be done with a custom editor, that converts the JSON into a UserProfile object:
public class UserProfileEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
ObjectMapper mapper = new ObjectMapper();
UserProfile value = null;
try {
value = new UserProfile();
JsonNode root = mapper.readTree(text);
value.setEmail(root.path("email").asText());
} catch (IOException e) {
// handle error
}
setValue(value);
}
}
This is for registering the editor in the controller class:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(UserProfile.class, new UserProfileEditor());
}
And this is how to use the editor, to unmarshall the JSONP parameter:
@RequestMapping(value = "/jsonp", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
SessionInfo register(@RequestParam("profileJson") UserProfile profileJson){
...
}
How to POST a JSON payload to a @RequestParam in Spring MVC
Yes,is possible to send both params and body with a post method:
Example server side:
@RequestMapping(value ="test", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Person updatePerson(@RequestParam("arg1") String arg1,
@RequestParam("arg2") String arg2,
@RequestBody Person input) throws IOException {
System.out.println(arg1);
System.out.println(arg2);
input.setName("NewName");
return input;
}
and on your client:
curl -H "Content-Type:application/json; charset=utf-8"
-X POST
'http://localhost:8080/smartface/api/email/test?arg1=ffdfa&arg2=test2'
-d '{"name":"me","lastName":"me last"}'
Enjoy
sending json object to GET method in spring MVC
You can't send JSON on the request parameter, directly. From the docs:
When an @RequestParam annotation is used on a Map or
MultiValueMap argument, the map is populated with all
request parameters.
I'm pretty sure you'll need to do something like call encodeURIComponent() on the json structure you want to pass to your server and then have the argument just be a string. On the server side you can use jersey or something to convert the string back into something you can manipulate.
This post may provide some more insight:
Spring MVC: Complex object as GET @RequestParam
Passing in JSON array to spring MVC Controller
try to add this to you ajax call it should fix the unsupported response :
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
this is a full example of ajax call that is working for me :
$.ajax({
dataType : "json",
url : this.baseurl + "/dataList",
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
data : JSON.stringify(params),
type : 'POST',
success : function(data) {
self.displayResults(data);
},
error : function(jqXHR,textStatus,errorThrown ){
showPopupError('Error','error : ' + textStatus, 'ok');
}
});
How to read Json object in spring mvc controller
Please check your content-type Try one of the two.
$.ajax({
url :'/users/edit',
type : 'POST',
contentType: "application/json", //either
beforeSend: function(xhr) {
//xhr.setRequestHeader("Content-Type", "application/json"); //or
},
data : dataObject,
success: function(data) {
}
});
Before
%7B%22username%22%3A%22quentin%22%7D=
After
{"username":"quentin"}
Spring MVC - How to return simple String as JSON in Rest Controller
Either return text/plain
(as in Return only string message from Spring MVC 3 Controller) OR wrap your String is some object
public class StringResponse {
private String response;
public StringResponse(String s) {
this.response = s;
}
// get/set omitted...
}
Set your response type to MediaType.APPLICATION_JSON_VALUE
(= "application/json"
)
@RequestMapping(value = "/getString", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
and you'll have a JSON that looks like
{ "response" : "your string value" }
Related Topics
What Are the Date Formats Available in Simpledateformat Class
Using Spring Resttemplate in Generic Method with Generic Parameter
Why String.Replaceall() in Java Requires 4 Slashes "\\\\" in Regex to Actually Replace "\"
Determining Current Call Stack (For Diagnostic Purposes)
Dynamic Generic Typing in Java
How to Load Files into My Java Application
How Are Constructors Called During Serialization and Deserialization
How Does System.Out.Print() Work
Random Number with Probabilities
Why Does Getrealpath() Return Null When Deployed with a .War File
How to Ignore Certain Elements When Comparing Xml
Printf %F with Only 2 Numbers After the Decimal Point
Differencebetween String and Stringbuffer in Java
Accessing a File Inside a .Jar File