Introduction to json format data conversion between java and javascript

Conversion between objects and strings in javascript 

Convert the object to a string: through the JSON.encode method, this is the method in json.js, just import it into the current file. 
Convert a string to an object: ①Use the JSON.decode method, as above, just import js. ②There is a method in jQuery, $.parseJson can also be implemented. 

Conversion between json string and object in java 

Convert the object to a string: There is a JsonUtil.serial method in struts2-json-plugin.jar. You can also customize it freely by yourself. It is realized by string splicing. If the attribute of the json string must be double quotes, single quotes or if it is not applicable, an error will be reported. eg: "{\"id\":123,\"name\":\"wch\",\"children\":[{\"id\":456}]}", the string is converted to an object 
: JsonObject.fromObject(), if it is an array, use JsonArray.fromObject(). There are only objects or arrays in the json object. However, this can only convert the current attribute. If there is an array or list in the object, it must be assigned and converted again. For example, you cannot complete the json string above in one step. Even if the object has an attribute of children, the list will not automatically convert the string to a list for you. 

convert java string to javascript object 

The contact between java and js will only happen in jsp (I currently think so), in jsp as long as var obj = <%=javaStr%> is enough. You can also assign to the string var obj = "<%=javaStr%>" in js first, and then use the string in the first step to convert it into an object. 

convert javascript string to java object 

If you want to implement it by yourself, ① first convert it to a string in js, and assign it to a property in java through parameter passing. ② Use the method of the second step to convert. If you use struts2, all this is so easy, all you have to do is define the attribute with the same name in the action. 

Guess you like

Origin blog.csdn.net/cdming/article/details/130279575