JS and Java use JSON methods to parse

Source: Internet
Author: User
Tags object object

JS and Java use JSON methods to parse

A. js section ==================

A method that converts a JSON string into a JSON object. In the process of data transfer, JSON is passed in the form of text, which is a string, and JS is the JSON object, so the conversion between JSON object and JSON string is the key.

For example:
JSON string:
var str1 = ' {' name ': ' cxh ', ' sex ': ' Man '} ';
JSON object:
var str2 = {"Name": "Cxh", "Sex": "Man"};

One, JSON string converted to JSON object
To use the above str1, you must first convert to a JSON object using the following method:
Converted from a JSON string to a JSON object var obj = eval (' (' + str + ') ');
Or
Or
Then, you can read this:
Alert (Obj.name); Alert (Obj.sex);
Special Note: If obj is originally a JSON object, then using the eval () function after conversion (even if multiple conversions) is a JSON object, but there is a problem with the Parsejson () function (throwing a syntax exception).
Second, the JSON object can be converted to a JSON string using tojsonstring () or global Method Json.stringify ().

For example:
Or
Converts the JSON object to the JSON character var last=json.stringify (obj); alert (last);
Attention:

In the above several methods, in addition to the eval () function is JS own, the other several methods are from the Json.js package. The new version of JSON modifies the API to inject json.stringify () and Json.parse () two methods into the Javascript built-in object, which becomes the object.tojsonstring (), and the latter becomes the Strin G.parsejson (). If you are prompted not to find the tojsonstring () and Parsejson () methods, your JSON package version is too low.

Two. Java Section ===============
1. Json-lib is a Java class library that provides the ability to convert Java objects, including beans, maps, collections, Java Arrays and XML, to JSON, or reverse-transform.
2. Json-lib Home: http://json-lib.sourceforge.net/
3. Execution Environment
The following class library support is required (MAVEN build)

    Pom.xml    <dependency>    <groupId>net.sf.json-lib</groupId>    <artifactId> json-lib</artifactid>    <version>2.4</version>    <classifier>jdk15</classifier >    </dependency>
The following table corresponds to the Java-JavaScript type.

code example:

Note: when converting a Json-formatted string to JavaBean, it is important to note that there must be no parameter constructor in the JavaBean, otherwise it will be reported that the initialization method cannot be found as follows

JavaBean Code:

Package Com.ppl.jsonconvert;public class Student {//name private string name;//age private String age;//address private string address;//when converting a Json-form string to JavaBean, it is important to note that the JavaBean must have a parameterless constructor, otherwise it will be reported that there is no error in the initialization method, public Student () {super ();} Public Student (string name, String age, string address) {super (); this.name = Name;this.age = Age;this.address = Address;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getage () {return age;} public void Setage (String age) {this.age = age;} Public String getaddress () {return address;} public void setaddress (String address) {this.address = address;} @Overridepublic String toString () {return "Student [name=" + name + ", age=" + Age + ", address=" + address + "]";}}

Provides two tool classes, JSON conversion map implementation method, a bit simple, to deal with simple requirements no problem

/*** * Parses a JSON-formatted string into a map object  * @param object *   JSON String * @return Map Collection */public   static map<string, String> ; Tohashmap (Object object)   {   linkedhashmap<string, string> dataMap = new linkedhashmap<string, String > ();       Converts a JSON string to Jsonobject       jsonobject jsonobject = Jsonobject.fromobject (object);       Iterator it = Jsonobject.keys ();       Traverse jsonobject data, add to map object while       (It.hasnext ())       {           String key = String.valueof (It.next ());           String value = (string) jsonobject.get (key);           Datamap.put (key, value);       }       return dataMap;   }

  /** * * JSON conversion map. * <br> Details * @param jsonstr JSON String * @return * @return map<string,object> Collection * @throws * @author SL J */public static map<string, object> Parsejson2map (String jsonstr) {listorderedmap Map = new Listorde        Redmap ();        Outermost parsing jsonobject json = Jsonobject.fromobject (JSONSTR);             For (object K:json.keyset ()) {Object v = json.get (k); If the inner layer is still an array, continue parsing if (v instanceof jsonarray) {list<map<string, object>> List = new A                Rraylist<map<string,object>> ();                Iterator<jsonobject> it = ((Jsonarray) v). Iterator ();                    while (It.hasnext ()) {Jsonobject json2 = It.next ();                List.add (Parsejson2map (json2.tostring ()));            } map.put (K.tostring (), list);            } else {map.put (k.tostring (), v);    }} return map; }

Test code:

Package Com.ppl.jsonconvert;import Java.util.arraylist;import Java.util.hashmap;import java.util.LinkedHashMap; Import Java.util.list;import java.util.map;import com.ppl.json.commons.jsonutils;import Net.sf.json.JSONArray; Import Net.sf.json.jsonobject;public class Test {@SuppressWarnings ({"Unused", "rawtypes", "Unchecked"}) public static void Main (string[] args) {///******************************//Ordinary Java entity class into a JSON string form///**************************** **student stu=new Student () stu.setname ("JSON"); Stu.setage ("at") stu.setaddress ("Xicheng District, Beijing");//1, Use Jsonobjectjsonobject Jsonobject = Jsonobject.fromobject (stu); String strjson=jsonobject.tostring ();//strjson:{"Address": "Xicheng District, Beijing", "age": "All", "name": "JSON"}system.out.println ( "Strjson:" +strjson);//2, use Jsonarrayjsonarray jsonarray=jsonarray.fromobject (STU); String strarray=jsonarray.tostring ();//strarray:[{"Address": "Xicheng District, Beijing", "age": "All", "name": "JSON"}] System.out.println ("Strarray:" +strarray);/////////////////////******************************//json WordString-"Java object///******************************//defines two different format strings objectstr=" {\ "name\": \ "jsonstu1\", \ "age\": \ " 18\ ", \" address\ ": \" Beijing Xicheng District \ "}"; String arraystr= "[{\" name\ ": \" jsonstu2\ ", \" age\ ": \" 22\ ", \" address\ ": \" Jinan Licheng District \ "}]";//1, Use jsonobject--to convert text columns to Jsonjsonobject jsonobject2=jsonobject.fromobject (OBJECTSTR); Student stu2= (Student) Jsonobject.tobean (JsonObject2, Student.class); System.out.println ("STU2:" +STU2);//2. Use jsonarray--to convert text columns to Jsonjsonarray jsonarray2=jsonarray.fromobject (arraystr )///Get the first element of Jsonarray object O=jsonarray2.get (0); Jsonobject Jsonobject3=jsonobject.fromobject (o); Student stu3= (Student) Jsonobject.tobean (JSONOBJECT3, Student.class); System.out.println ("STU3:" +stu3)///******************************//map converted to JSON, mostly using jsonobject (note 1)///********** Not recommended for use from org.apache.commons.collections.orderedmap//map<string, integer> Ordermap = ( Map<string, integer>) new Listorderedmap ();//ordered Mapmap Ordermap = new linkedhashmap<string, String> (); Map map = new Hashmap<string,object> ();          Map.put ("name", "JSON");          Map.put ("bool", boolean.true);          Map.put ("int", new Integer (1));          Map.put ("arr", New string[]{"A", "B"});                    Map.put ("func", "function (i) {return this.arr[i];}");          Jsonobject Jsonobjectmap = jsonobject.fromobject (map);                  System.out.println ("Map converted to JSON:" +jsonobjectmap);                 Note 1 Examples are detailed Student stu4=new Student ("JSON", "28", "Shanghai");        Map<string,student> map4=new hashmap<string,student> ();        Map4.put ("First", STU4);        1, Jsonobject jsonobject mapobject=jsonobject.fromobject (MAP4);        System.out.println ("MapObject" +mapobject.tostring ());        2, Jsonarray Jsonarray maparray=jsonarray.fromobject (MAP4);                      System.out.println ("Maparray:" +maparray.tostring ()); list--"JSON string, using Jsonarray///***************************** * Student stu5=new Student ("Student1", "+", "Jinan");        Student stu6=new Student ("Student2", "N", "Qingdao");        List<student> lists=new arraylist<student> ();        Lists.add (STU5);        Lists.add (STU6);                 1, using Jsonarray jsonarray listarray=jsonarray.fromobject (lists);              System.out.println ("Listarray:" +listarray.tostring ()); JSON string--"list///****************************** string arraystr      2= "[{\" name\ ": \" json\ ", \" age\ ": \" 24\ ", \" address\ ": \" Jinan hi-tech zone \ "}]"; Convert to List list<student> list2= (list<student>) jsonarray.tolist (Jsonarray.fromobject (ARRAYSTR2),      Student.class);          for (Student stus:list2) {System.out.println (stus);       }//The newest method JSON string--"list Jsonarray Jsonarrayt = Jsonarray.fromobject (ARRAYSTR2);       List<student> ListData = (List) jsonarray.tocollection (Jsonarrayt, Student.class); for (StUdent stus:listdata) {System.out.println ("ListData:" +stus);      }//Convert to array student[] SS = (student[]) Jsonarray.toarray (Jsonarray.fromobject (ARRAYSTR), student.class);          for (Student student:ss) {System.out.println (Student);            }///******************************//json string--"Map///****************************** Bug___________________todo----------BUG String strobject= "{\" key\ ": {\" address\ ": \" Shanghai, China \ ", \" age\ ": \" 23\ ", \" name      \ ": \" json\ "}}";      map<string, string> dataMap = Jsonutils.tohashmap (strobject);     System.out.println (Datamap.tostring ()); }}




JS and Java use JSON methods to parse

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.