Java uses Jsonobject-lib to parse JSON strings

Source: Internet
Author: User

Direct code: (Required jar: Json-lib.jar, may be associated with some other jar package, please search by yourself.)

Import Java.util.arraylist;import java.util.hashmap;import Java.util.iterator;import Java.util.List;import Java.util.map;import Net.sf.json.jsonarray;import Net.sf.json.jsonobject;public class JsonParser {@SuppressWarnings ("Rawtypes") public void Test () {Map m = This.testjson ("jsonstring"); System.out.println ((Map) ((List) m.get ("Test")). Get (0)). Get ("Test_title")); @SuppressWarnings ({"Rawtypes", "Unchecked"}) public Map Testjson (String str) {Jsonobject JSON = Jsonobject.fromobject ( STR);iterator<?> it = Json.keyset (). Iterator (); Map map = new HashMap (); while (It.hasnext ()) {string key = (String) it.next (); String value = json.getstring (key), if (this.isstring (value)) {Map.put (key, value);} if (This.isjson (value)) {Map.put (Key, This.testjson (value));} if (This.isjsonarray (value)) {Map.put (Key, This.testjsonarray (value));}} return map;} @SuppressWarnings ({"Unchecked", "rawtypes"}) public List Testjsonarray (String str) {Jsonarray Jsonarr = Jsonarray.fromobject (str); List List = new ArraylisT (); for (Object Json:jsonarr) {List.add (This.testjson (json.tostring ()));} return list;} public Boolean Isjson (String s) {Boolean flag = True;try {Jsonobject.fromobject (s);} catch (Exception e) {flag = false;} return flag;} public Boolean Isjsonarray (String s) {Boolean flag = True;try {Jsonarray.fromobject (s);} catch (Exception e) {flag = False ;} return flag;} public Boolean isstring (String s) {return!this.isjson (s) &&!this.isjsonarray (s);} public static void Main (string[] args) {Jsonparser TJ = new Jsonparser (); Tj.test ();}}

Java uses Jsonobject-lib to parse JSON strings

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.