Package to be introduced:
jakarta commons-lang 2.3 jakarta commons-beanutils 1.7.0 jakarta commons-collections 3.2 jakarta commons-logging 1.1 ezmorph 1.0.4 json-lib-2.4-jdk15.jar
Product. Java
public class Product {private String product;private double price;private Object item;public Object getItem() {return item;}public void setItem(Object item) {this.item = item;}public String getProduct() {return product;}public void setProduct(String product) {this.product = product;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}}
Jsonutil. Java
Public class jsonutil {// {"product": "penpencil", "price": 12, "item": [{"ID": 1, "name ": "Chen"}]} Private Static final string jsostr = "{\" Product \ ": \" penpencil \ ", \" Price \ ": 12, \" item \": [{\ "ID \": 1, \ "Name \": \ "Chen \"}]} "; public static void main (string [] ARGs) throws ioexception {// stringsystem. out. println (string4json ("key", "20"); // objproduct P = (product) getobject4jsonstring (jsostr, product. class); system. out. println (P. getproduct () + "," + P. getprice (); // mapmap map = getmap4json (jsostr); For (iterator = map. entryset (). iterator (); iterator. hasnext ();) {map. entry entry = (map. entry) iterator. next (); system. out. println (entry. getkey () + "," + entry. getvalue ();} // array object [] objects = getstringarray4json (jsostr); For (INT I = 0; I <objects. length; I ++) {system. out. println (objects [I]) ;}// convert string to jsonpublic static string string4json (string key, string value) throws jsonexception {jsonobject object = new jsonobject (); object. put (Key, value); return object. tostring () ;}// get a Java object public static object getobject4jsonstring (string jsonstring, class pojocalss) {object pojo; jsonobject = jsonobject from the JSON object character format. fromobject (jsonstring); pojo = jsonobject. tobean (jsonobject, pojocalss); Return pojo;} // obtain a mappublic static map getmap4json (string jsonstring) {jsonobject = jsonobject from the JSON expression. fromobject (jsonstring); iterator keyiter = jsonobject. keys (); string key; object value; Map valuemap = new hashmap (); While (keyiter. hasnext () {key = (string) keyiter. next (); value = jsonobject. get (key); valuemap. put (Key, value) ;}return valuemap;} // get a Java object list from the JSON object set expression public static list getlist4json (string jsonstring, class pojoclass) {jsonarray = jsonarray. fromobject (jsonstring); jsonobject; object pojovalue; List list = new arraylist (); For (INT I = 0; I <jsonarray. size (); I ++) {jsonobject = jsonarray. getjsonobject (I); pojovalue = jsonobject. tobean (jsonobject, pojoclass); list. add (pojovalue);} return list;} // parse the Java String Array public static object [] getstringarray4json (string jsonstring) {jsonobject jsonobj = jsonobject from the JSON array. fromobject (jsonstring); jsonarray jsonarr = jsonobj. getjsonarray ("item"); Return (object []) jsonarr. toarray ();}