JSON and string/array/collection conversion of God Operation Summary

Source: Internet
Author: User
Tags parse error string to json

One: 4 ways of front-end string to JSON

1,eval way to parse, I am afraid this is the earliest way to parse.

function Strtojson (str) {     var json = eval (' (' + str + ') ');      return JSON;}

2,new function form, more strange oh.

function Strtojson (str) {    var json = (new Function ("return" + str));     return JSON;}

IE6/7 when a newline (\ n) is contained in a string, the new function cannot be parsed, but Eval is ok.

3, use a global JSON object.

function Strtojson (str) {    return  json.parse (str);}

The method is currently implemented by IE8 (S)/firefox3.5+/chrome4/safari4/opera10.

Use Json.parse strict adherence to the JSON specification, such as attributes are required in quotation marks, as follows

var str = ' {name: ' Jack '} '; var // -- Parse error

The name is not enclosed in quotation marks, and the parsing fails with the exception thrown in all browsers using Json.parse. And the first two ways are fine.

How the 4,jquery plugin supports conversion


Two. String to JSON format in Java

1. Constructing methods using the Jsonobject class

 Public class Demo {      publicstaticvoidthrows  Exception {          = "{\" A\ " : \ "B\", \ "c\": \ "d\"} ";           New jsonobject (str);           // {"C": "D", "a": "B"}          // D       }  }  

2. Using the Jsonobject Fromobject (jsonstr) method

import net.sf.json.*// string {"id": 1}int jsid = Integer.parseint ( Jsstr.getstring ("id")); // gets the value of the ID

Three. String to JSON format array in Java and traverse

//When you need to turn a string of strings into a JSON array and iterate through the contents. //Home Import Net.sf.json.JSONArray and net.sf.json.JSONObject two jar packagesString str= "[{name: ' A ', Value: ' AA '},{name: ' B ', value: ' BB '},{name: ' C ', Value: ' CC '},{name: ' d ', value: ' DD '}]";//a non-converted stringJsonarray JSON = Jsonarray.fromobject (str);//first turn the string into a Jsonarray objectif(Json.size () >0){   for(intI=0;i<json.size (); i++) {Jsonobject job= Json.getjsonobject (i);//iterate through the Jsonarray array and turn each object into a JSON objectSystem.out.println (Job.get ("name") + "=");//get the property values in each object  }}

Four. The collection type operation in the string to JSON format in Java

Map Turn string

Map<string, string> map=new hashmap<string, string>(); Map.put ("name", "Dr. Sisi"); Map.put ("age", "+"); Jsonobject jsonobject=jsonobject.fromobject (map); String res=jsonobject.tostring (); System.out.println (res);

Result: {"age": "+", "name": "Dr. Sisi"}

List Turn string

list<string> list=New arraylist<string>() list.add ("China"); List.add ("People") ); List.add ("Republic");        Jsonarray Jsonarray=jsonarray.fromobject (list); String res=jsonarray.tostring (); System.out.println (res);

Results: ["China", "people", "republic"]

String goto Map

String res= "{\" age\ ": \" 25\ ", \" name\ ": \" Sisi dr \ "}"; // or so // res= "{' Age ': ' + ', ' name ': ' Dr. Sisi '}"; Jsonobject jsonobject=Jsonobject.fromobject (res); Map<String,String> map = (hashmap<string,string>) Jsonobject.tobean (Jsonobject, HashMap.  Class); SYSTEM.OUT.PRINTLN (map); System.out.println (Map.size ()); System.out.println (Map.get ("name")); System.out.println (Map.getclass (). GetName ());


{Dr. Name= Sisi, age=25}
Dr. Sisi

String into our custom class

 PackageJSON; Public classUserBean {PrivateString name; PrivateString age;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString getage () {returnAge ; }     Public voidsetage (String age) { This. Age =Age ; } }
String UserS = "{' name ': ' Dr. Sisi ', ' age ': '+ ' == (UserBean) jsonobject.tobean (obj, UserBean.  Class); System.out.println (Userbean.getname ());

string conversion to the array (the original is converted to list, I tried it, no, these are the JSON tool class extension, not necessarily fly to use, but in order to look Bull X, or more decorate it)

String arraystring= "[' A ', ' B ', ' CCC ']"; Jsonarray Jsonarray=jsonarray.fromobject (arraystring); object[] arr=jsonarray.toarray (); System.out.println (arr.length); System.out.println (arr[2]);

One, front-end JSON-to-string or parse JSON-formatted data

var a={"name": "Tom", "Sex": "Male", "Age": "$"};    var b= ' {' name ': ' Mike ', ' sex ': ' Female ', ' age ': ' "} ';    var atostr=json.stringify (a);    var btoobj=Json.parse (b);   Alert (typeof(ATOSTR));  // string    Alert (typeof(btoobj)); // Object  

1>jquery plug-in supported conversion mode:

$.parsejson (JSONSTR); Jquery.parsejson (JSONSTR), you can convert a JSON string into a JSON object
2> Browser supported conversion mode (FIREFOX,CHROME,OPERA,SAFARI,IE9,IE8) and other browsers:

Json.parse (JSONSTR); You can convert a JSON string into a JSON object
Json.stringify (Jsonobj); You can convert a JSON object to a JSON string
Note: IE8 (compatibility mode), IE7 and IE6 do not have JSON objects, it is recommended to use the official JSON method, the introduction of Json.js.

3>javascript Supported conversion modes:
Eval (' (' + jsonstr + ') '); You can convert a JSON string to a JSON object, noting that you need to wrap a pair of parentheses outside the JSON character
Note: IE8 (compatibility mode), IE7 and IE6 can also use eval () to convert strings to JSON objects, but these methods are not recommended, which is unsafe for eval to execute an expression in a JSON string.

4>json official Way of conversion:
http://www.json.org/provides a json.js so that IE8 (compatibility mode), IE7 and IE6 can support JSON objects as well as their stringify () and Parse () methods;
Can get this JS on Https://github.com/douglascrockford/JSON-js, generally now use json2.js.


JSON and string/array/collection conversion of God Operation Summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.