I want to add JSONArray in spring's model attribute and return from ModelAndView Controller. Not able to do like below. Request for help. Thanking you!
#RequestMapping(value = "/sample.htm", method = RequestMethod.GET)
public ModelAndView seatRequest( ModelMap model,
HttpServletRequest request,HttpServletResponse response, HttpSession session) throws JSONException, JsonProcessingException {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("0", "val0");
jsonObject.put("1", "val1");
jsonObject.put("2", "val2");
jsonArray.put(jsonObject);
model.addAttribute("jsonData",jsonArray.toString());
return new ModelAndView("sample");
What is your intention? Currently JsonArray is added in String form.You can access this jsonArray as a String in your view. But I think you don't want to do that. If you want to access it as object just add as model.addAttribute("jsonData",jsonArray) and then you can access it as object in your views.
Also, In your json Object, Key value is Numric "0","1" so on. make it alphanumeric i.e "key1", "key2" etc. and values "val1","val2" etc. Because name of identifiers cannot start with numbers.
Related
I have json object as below
{'key_1':'value_1','key_2':'value_2','key_3':'value_3',.....'key_N':'value_N',}
i tried to map this json with HashMap<String,String>, but it does not worked for me.
if any one have solution to map above json with proper datatype in #RequestBody in spirng controller would be appreciated.
Thanks
As per question, you can not hold many number of json values in the Map object or any other object because it will become heavy object and may cause memory leaks.
You can add required values to Map or any other object and send response to the client.
Note: it should not be a heavy object because it will impact in the real time environment while concurrency.
However you can use below snippet:
#RequestMapping(value = "/someUrl", method = RequestMethod.POST)
public #ResponseBody ResponseEntity<Object> someMethod(final HttpServletRequest req, final HttpSession session) {
ResponseEntity<Object> responseEntity;
Map<String,String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", "value4");
map.put("key5", "value5");
map.put("key6", "value6");
map.put("key7", "value7");
map.put("key8", "value8");
map.put("key9", "value9");
responseEntity = new ResponseEntity<Object>(map, HttpStatus.OK);
return responseEntity;
}
I have a rest controller returning a json list of objects. When I call method 1) it works as required.
When I need to configure serialisation to ignore certain properties in one request but not the other, I am using mixIn annotation and objectMapper. When I return the object it is in xml instead of json as before. Can anybody help? I realise I am now returning a string but if I want the same respose as 1) do I need to convert string to object and return in responseEntity as before.
1)
#RequestMapping(value = "/search", method = RequestMethod.POST)
public ResponseEntity<List<MyObject>> search(#RequestBody SearchParams searchParams){
List<MyObject> result = myService.find(searchParams);
return new ResponseEntity<List<MyObject>(result, HttpStatus.OK);
}
returns
[
{"prop1":"val1", "prop2":"val2"},
{"prop1":"val3", "prop2":"val4"}
]
2)
#RequestMapping(value = "/search", method = RequestMethod.POST)
public ResponseEntity<String> search(#RequestBody SearchParams searchParams){
List<MyObject> result = myService.find(searchParams);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getSerializationConfig().addMixInAnnotations(MyObject.class, MyObjectFilter.class);
String json = objectMapper.writeValueAsString(result);
return new ResponseEntity<String>(json, HttpStatus.OK);
}
returns
<data contentType="text/plain;charset=ISO-8859-1" contentLength="*"><![CDATA[
[
{"prop1":"val1", "prop2":"val2"},
{"prop1":"val3", "prop2":"val4"}
]
]]></data>
This appears in xml tab in soapui instead of json tab. Can anybdy help?
I am trying to send an object via an ajax POST using JSON payload; this object has references to other objects stored in a database, handled by Hibernate; I need to access this database to resolve other objects references and store them in the new object obtained deserializing JSON payload of request.
Now, I have to access HttpServletRequest attribute in order to get a saved hibernate session to use to access to database. Is it possible?
The controller that handle the request is the following:
#RequestMapping(value = "/newproduct", method = RequestMethod.POST)
public #ResponseBody
Integer newProduct(HttpServletRequest request, #RequestBody Product product)
{
//Controller code here
}
The deserializer where I have to be able to get request attribute "hibernate_session" is a custom deserializer, registered to Jackson and is the following:
public class ProductDeserializer extends JsonDeserializer<Product>
{
#Override
public Product deserialize(JsonParser jpar, DeserializationContext arg1)
throws IOException, JsonProcessingException
{
Product newProduct = new Product();
// I want to get request attribute or open a new hibernate session here
return newProduct;
}
}
If necessary I'll post more code if needed.
Thanks
You may try following approach
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
I'm using Spring MVC, and I need return in the Controller, a Json object that contains the view, by example, the related jsp page.
return: { name: "fragment-form", other-info:"other-info", view: view}
where "view" should be the JSP page linked to your ModelAndView
I read other post, but I not find the solution, because I need that controller to the work, if it's posible.
Sugestions?
EDIT:
I have a form with your values, and the submit, from javascript execute this follow code:
#RequestMapping(method = RequestMethod.POST)
public Object create(#Valid #RequestBody PatientForm form, HttpServletResponse response) {
ModelMap map = new ModelMap();
map.put("form", form);
return new ModelAndView("addPatientForm", map);
}
I need return a Json where the "ModelAndView("addPatientForm", map)" processed within the json that is returned.
Would something like this work for you:
#RequestMapping(value="/somepage", method=RequestMethod.POST)
public ResponseEntity<String> generateViewasJSON(){
JSONObject json = new JSONObject();
json.put("name","fragment-form");
...
HttpHeaders headers = new HttpHeaders();
headers.set( "Content-Type", "application/json" );
return new ResponseEntity<String>( json.toString(), headers, HttpStatus.OK );
}
I am writing code that needs to extract an object literal posted to a servlet. I have studied the API for the HttpServletRequest object, but it is not clear to me how to get the JSON object out of the request since it is not posted from a form element on a web page.
Any insight is appreciated.
Thanks.
are you looking for this ?
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} finally {
reader.close();
}
System.out.println(sb.toString());
}
This is simple method to get request data from HttpServletRequest
using Java 8 Stream API:
String requestData = request.getReader().lines().collect(Collectors.joining());
make use of the jackson JSON processor
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(request.getInputStream(),Book.class);
The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:
BufferedReader reader = request.getReader();
Gson gson = new Gson();
MyBean myBean = gson.fromJson(reader, MyBean.class);
There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request
String jsonString = IOUtils.toString(request.getInputStream());
Then you can do whatever you want, convert it to JSON or other object with Gson, etc.
JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..
If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.
Converting the retreived data from the request object to json object is as below using google-gson
Gson gson = new Gson();
ABCClass c1 = gson.fromJson(data, ABCClass.class);
//ABC class is a class whose strcuture matches to the data variable retrieved