This article mainly uses json to interact with Ajax data at the front end in java.
1. First, the front-end uses Ajax. Note that dataType must select the json mode. The Json content returned by Action to the page is [{"number": "V006 ", "names": "LiLei"}], you can see that 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 ("student ID" + comment ['number']) ;}) ;}});
2. the Ajax URL points to the mystudent method in the java action. The returned list is actually an object Student, including the names and nunmber fields.
Public String mystudent () throws Exception {List list = priceService. query (); // call the interface implementation class this. jsonUtil (list); return null ;}
3. On the action page, write a method jsonUtil as the json method.
// Call the json method and input the parameter alistpublic 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 am using a newer 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;}}