Conversion of Json object to Json string, conversion of JSON string to Java object

1. Conversion of Json objects and Json strings 1.

Conversion methods supported by the jQuery plug-in:
 
$.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr), can convert json string into json object


2. Conversion methods supported by browsers (Firefox, chrome, opera, safari, ie9, ie8) and other browsers:

  JSON.stringify(obj) converts JSON to string. JSON.parse(string) converts the string to JSON format;

var a={"name":"tom","sex":"男","age":"24"};
var b='{"name":"Mike","sex":"女","age":"29"}';
var aToStr=JSON.stringify(a);
var bToObj=JSON.parse(b);
alert(typeof(aToStr));  //string
alert(typeof(bToObj));//object


3. Conversion methods supported by Javascript:
eval('(' + jsonstr + ')'); //You can convert a json string into a json object, note that you need to wrap a pair of parentheses around the json character

quote
Note: ie8 (compatibility mode), ie7 and ie6 can also use eval() to convert strings to JSON objects, but these methods are not recommended. This method is unsafe and eval will execute expressions in JSON strings.


4. The official JSON conversion method:
http://www.json.org/ provides a json.js, so that ie8 (compatibility mode), ie7 and ie6 can support JSON objects and their stringify() and parse() methods ;
You can get this js on https://github.com/douglascrockford/JSON-js, and generally use json2.js now.

Second, the conversion of JSON strings and java objects

1. Convert the list of java objects to an array of json objects, and convert them to strings
  
JSONArray array = JSONArray.fromObject(list);
    String jsonstr = array.toString();




2. Convert java objects to json objects and convert them to strings
 
JSONObject object = JSONObject.fromObject(user);
  Log4jInit.ysulogger.debug(object.toString());




3. Convert JSON string to JAVA object array
 
JSONArray json = JSONArray.fromObject(userStr);//userStr是json字符串
  List<User> users= (List<User>)JSONArray.toCollection(json, User.class);


4. Convert JSON string to JAVA object
  
JSONObject jsonobject = JSONObject.fromObject(jsonStr);
  User user= (User)JSONObject.toBean(object,User.class);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326158257&siteId=291194637