This article is mainly for you to share Ajax to obtain a display of JSON data, a method for everyone to reference, the specific contents are as follows
1, first foreground with Ajax, which note datatype must select JSON, action successfully returned to the page of the JSON content is this [{"Number": "V006", "names": "Lilei"}], visible comment[' names '] corresponds to "names": "Lilei", comment[' number '] corresponds to "number": "V006".
$.ajax ({
type: Post),
URL: ' apply/mystudent.action? ',
Cache:false,
dataType: "JSON",
success : function (data) {
$.each (data, function (Commentindex, comment) {
alert ("name" + comment[' names '));
Alert ("School number" +comment[' numbers ');});});
2, the Ajax URL points to the Java action in the Mystudent method, the return list is actually an object student, including the names and Nunmber fields
Public String mystudent () throws exception{
List list=priceservice.query ();//Invoke Interface implementation class
This.jsonutil (list);
return null;
}
3, the action page is dedicated to write a method Jsonutil as a JSON method
Invokes the JSON tool method, passing in the parameter alist public
void Jsonutil (Object accountlist) throws Exception {
HttpServletResponse Response = Servletactioncontext.getresponse ();
Log.info ("JSON format:" + accountlist.tostring ());
String Returnjson = Jsonconvert.returnjson (accountlist);
Response.setcharacterencoding ("Utf-8");
Response.getwriter (). println (Returnjson);
4. I'm using a new JSON package, Jackson.
Import Java.io.StringWriter;
Import Org.codehaus.jackson.map.ObjectMapper;
public class JsonConvert {
static String jsonstr;
public static String Returnjson (Object object) throws exception{
objectmapper objectmapper = new Objectmapper ();
StringWriter StringWriter = new StringWriter ();
Objectmapper.writevalue (StringWriter, object);
Jsonstr = Stringwriter.tostring ();
Return Jsonstr
}
}
The above is the entire content of this article, I hope to help you learn.