Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

Best way to create a json

HI,
In my spring mvc application i am creating a json like :
 @RequestMapping(value = "/snippets", method = RequestMethod.POST)
    public void createSnippet(@RequestBody String jsonString, HttpServletResponse response, HttpServletRequest request) throws IOException {
        Snippet snippet = new ObjectMapper().readValue(jsonString, Snippet.class);
        String uuid = snippetDao.insertData(snippet);
        response.addHeader("Location", "http://" + request.getHeader("Host") + "/snippets/" + uuid);
        response.setStatus(201);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        String snippetURL = snippetURL(uuid, "/raw");
        String filename = snippetFilename(snippet.getTitle(), snippet.getMode());
        int size = snippet.getText().length();
        String json = "{\"download\" : {\"URL\": \""+snippetURL+"\",\"filename\":\""+filename+"\",\"size\":"+size+"}}";
        response.getWriter().write(json);
    }

Open in new window


In the above code this is the line i am talking about :        String json = "{\"download\" : {\"URL\": \""+snippetURL+"\",\"filename\":\""+filename+"\",\"size\":"+size+"}}";
Althouth its just one line... but wondering if there is a better way to write this ?
Also in the line        response.getWriter().write(json);
Now this json is referred in the ajax call in the javascript code... So i am passing it this way... Please
comment on this... if this is a correct way to do this ?
This code is in controller... Should this be better moved to service ?
Thanks
ASKER CERTIFIED SOLUTION
Avatar of gurpsbassi
gurpsbassi
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial