Ok, so I\'ve been looking at this for a little while now and am no further on. I\'ve got a Spring MVC servlet that I need to accept JSON from a JavaScript front end web app
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar
import net.sf.json.JSONObject;
...
public void send()
{
//put attributes
Map m = New HashMap();
m.put("send_to","my@admin.lan");
m.put("email_subject","this is a test email");
m.put("email_content","test email content");
//generate JSON Object
JSONObject json = JSONObject.fromObject(content);
String message = json.toString();
...
}
public void receive(String jsonMessage)
{
//parse attributes
JSONObject json = JSONObject.fromObject(jsonMessage);
String to = (String) json.get("send_to");
String title = (String) json.get("email_subject");
String content = (String) json.get("email_content");
...
}
More samples here http://json-lib.sourceforge.net/usage.html