Several methods of Java background parsing JSON

Source: Internet
Author: User
Tags object object string format

1. Object to JSON object.
public static void Main (string[] args) {Domain demo = new domain ("online JSON checksum format tool-sojson online tool (sojson.com)", "HTTP/ www.sojson.com/"," provides JSON online format, JSON online Format tool, JSON formatted output, JSON formatted empty string, JSON format plugin, JSON string formatting, JSON view, JSON online validation, JSON online viewer. "); String Objecttojson = Objecttojson (demo); System.out.println (Objecttojson);} public static String Objecttojson (Domain demo) {return Jsonobject.fromobject (demo). toString (); /** * Result output:  {    "description": "Provide JSON online format, JSON online Format tool, JSON formatted output, JSON formatted empty string, JSON format plugin, JSON string format, JSON view, JSON online validation, JSON online viewer. ",    " title ":" Online JSON check format tool-sojson online tool (sojson.com) ",    " url ":" http://www.sojson.com/"}  */

  

2.map<string,object> to JSON object.
public static void Main (string[] args) {map map = new HashMap (); Map.put ("title", "Online JSON check format tool-sojson online tool (sojson.com)") ; Map.put ("url", "http://www.sojson.com/"); Map.put ("description", "Provide JSON online format, JSON online Format tool, JSON formatted output, JSON format empty string, JSON format plugin, JSON string formatting, JSON view, JSON online validation, JSON online viewer. "); String Objecttojson = Maptojson (map); System.out.println (Objecttojson);} public static String Maptojson (map map) {return jsonobject.fromobject (map). ToString (); /** * Result output: {    "description": "Provide JSON online format, JSON online Format tool, JSON formatted output, JSON formatted empty string, JSON format plugin, JSON string format, JSON view, JSON online validation , the JSON online viewer. ",    " title ":" Online JSON check format tool-sojson online tool (sojson.com) ",    " url ":" http://www.sojson.com/"}  */

  

3. Conversion between object and JSON (Jsonutil).
Package Snippet;import Java.util.arraylist;import Java.util.collection;import java.util.hashmap;import Java.util.iterator;import Java.util.list;import Java.util.map;import Net.sf.ezmorph.object.datemorpher;import Net.sf.json.jsonarray;import Net.sf.json.jsonobject;import Net.sf.json.jsonconfig;import Net.sf.json.processors.jsdatejsonvalueprocessor;import Net.sf.json.util.jsonutils;public class JsonUtil {/** When the page passes to the background, the JSON data in the request parameter name */public final static string json_attribute = "JSON";p ublic final static string json_attribut E1 = "Json1";p ublic final static string json_attribute2 = "Json2";p ublic final static string json_attribute3 = "Json3";p UB  LIC final static String json_attribute4 = "Json4";/** * Gets a Java object from a JSON object character format, such as: {"id": Idvalue, "name": Namevalue, * "Abean": {"Abeanid": Abeanidvalue, ...} * * @param Object * @param clazz * @return */public static object Getdto (String jsonstring, Class clazz) {jsonobject JSON Object = null;try {Setdataformat2java (); jsonobject = JSONobject.fromobject (jsonstring);} catch (Exception e) {e.printstacktrace ();} Return Jsonobject.tobean (Jsonobject, clazz);} /** * Get a Java object from a JSON object character format, where Beanslist is a collection of a type, such as: {"id": Idvalue, "name": * namevalue, "Abean": {"Abeanid": Abeani Dvalue, ...}, beanslist:[{}, {}, * ...]} * * @param jsonstring * @param clazz * @param map * Collection Property type (key: Collection property name, Value: Collection attribute type Class) eg: ("beanslist ": * bean.class) * @return */public static Object getdto (String jsonstring, class Clazz, map map) {Jsonobject Jsonobject = null;try {Setdataformat2java (); jsonobject = Jsonobject.fromobject (jsonstring);} catch (Exception e) { E.printstacktrace ();} Return Jsonobject.tobean (Jsonobject, clazz, map);} /** * Get an array of Java objects from a JSON array, such as: [{"id": Idvalue, "name": Namevalue}, {"id": * idvalue, "name": Namevalue}, ...] * * @ Param Object * @param clazz * @return */public static object[] Getdtoarray (String jsonstring, Class clazz) {SETDATAFORMAT2 JAVA (); Jsonarray array = Jsonarray.fromobjecT (jsonstring); object[] obj = new Object[array.size ()];for (int i = 0; i < array.size (); i++) {Jsonobject Jsonobject = a Rray.getjsonobject (i); Obj[i] = Jsonobject.tobean (Jsonobject, clazz);} return obj;} /** * Get an array of Java objects from a JSON array, such as: [{"id": Idvalue, "name": Namevalue}, {"id": * idvalue, "name": Namevalue}, ...] * * @ Param Object * @param clazz * @param map * @return */public static object[] Getdtoarray (String jsonstring, Class clazz, Ma P map) {Setdataformat2java (); Jsonarray array = jsonarray.fromobject (jsonstring); object[] obj = new Object[array.size ()];for (int i = 0; i < array.si Ze (); i++) {Jsonobject jsonobject = Array.getjsonobject (i); Obj[i] = Jsonobject.tobean (Jsonobject, clazz, map);} return obj;}  /** * Get a collection of Java objects from a JSON array * * @param object * @param clazz * @return */public static List getdtolist (String jsonstring, Class clazz) {Setdataformat2java (); Jsonarray array = jsonarray.fromobject (jsonstring); List List = new ArrayList (); for (Iterator iter = Array.iterator (); iteR.hasnext ();) {Jsonobject Jsonobject = (jsonobject) iter.next (); List.add (Jsonobject.tobean (Jsonobject, Clazz));} return list;} /** * Gets a collection of Java objects from a JSON array where the object contains the collection properties * * @param object * @param clazz * @param map * Collection Property type * @return */p Ublic static List getdtolist (String jsonstring, Class clazz, map map) {Setdataformat2java (); Jsonarray array = jsonarray.fromobject (jsonstring); List List = new ArrayList (); for (Iterator iter = Array.iterator (); Iter.hasnext ();) {Jsonobject Jsonobject = (jsonobject) iter.next (); List.add (Jsonobject.tobean (Jsonobject, Clazz, map));} return list;} /** * Gets a map from the JSON hash expression that supports nested functions such as: {"id": "Johncon", "Name": "Johnny"} * Note Commons *-collections version, must contain org.apache.co MMONS.COLLECTIONS.MAP.MULTIKEYMAP * * @param object * @return */public static map Getmapfromjson (String jsonstring) {setd Ataformat2java (); Jsonobject jsonobject = Jsonobject.fromobject (jsonstring); Map map = new HashMap (); for (Iterator iter = Jsonobject.keys (); Iter.hasnext ();) {String key = (String) iter.next (); Map.put (Key, Jsonobject.get (key));} return map;} /** * Get the corresponding Java array JSON shape from the JSON array such as: ["123", "456"] * * @param jsonstring * @return */public static object[] Getobjectarrayfro Mjson (String jsonstring) {Jsonarray Jsonarray = Jsonarray.fromobject (jsonstring); return Jsonarray.toarray ();}  /** * Converts a data object into a JSON string Dto object shape such as: {"id": Idvalue, "name": Namevalue, ...} * Array object shape such as: [{}, {}, {}, ...] Map object shape: {key1: {"id": Idvalue, "name": * Namevalue, ...}, Key2: {}, ...} * * @param object * @return */public static String getjsonstring (Object object) throws Exception {String jsonstring = nul l;//Date value Processor Jsonconfig Jsonconfig = new Jsonconfig (); Jsonconfig.registerjsonvalueprocessor (java.util.date.class,new  Jsondatevalueprocessor ()); if (Object! = null) {if (object instanceof Collection | | object instanceof object[]) {jsonstring = Jsonarray.fromobject (object, Jsonconfig). toString ();} else {jsonstring = Jsonobject.fromobject (object, Jsonconfig). toString ();}} return jsonstring = = null? "{}": jsonstring;} private static void Setdataformat2java () {//Set Date conversion format Jsonutils.getmorpherregistry (). Registermorpher (New Datemorpher ( New string[] {"Yyyy-mm-dd", "Yyyy-mm-dd HH:mm:ss"})); public static void Main (string[] arg) throws Exception {String s = "{status: ' Success '}"; System.out.println ("object:" + jsonutil.getjsonstring (s));}}

  

4. Date Processing class
Package Snippet;import Java.text.simpledateformat;import Java.util.date;import net.sf.json.jsonarray;import Net.sf.json.jsonobject;import Net.sf.json.jsonconfig;import net.sf.json.processors.jsonvalueprocessor;/* * @author  www.sojson.com * Created Date 2008-9-10 * JSON Date value Processor */public class Jsondatevalueprocessor implements Jsonvalueprocessor {private string format = "Yyyy-mm-dd HH:mm:ss";p ublic static void Main (string[] args) {//three resolves the following example String rowidstring = "[{\" kl_id\ " : \ "2\", \ "kl_title\": \ "Test date\", \ "kl_content\": \ "Test date\", \ "kl_type\": \ "1\", \ "id\": \ "1\"},{\ "kl_id\": \ "2\", \ "kl_title\": \ "test\", \ "kl_content\": \ "test\", \ "kl_type\": \ "1\", \ "id\": \ "2\"}] "; Jsonarray array = jsonarray.fromobject (rowidstring); object[] obj = new Object[array.size ()];for (int i = 0; i < ARRAY.S Ize (); i++) {Jsonobject jsonobject = Array.getjsonobject (i); System.out.println (Jsonobject.get ("kl_id"));}} Public Jsondatevalueprocessor () {}public jsondatevalueprocessor (String format) {this.format = format;} Public objecT Processarrayvalue (Object value, Jsonconfig jsonconfig) {return process (value, jsonconfig);} Public Object Processobjectvalue (String key, Object Value,jsonconfig Jsonconfig) {return process (value, jsonconfig);} Private object Process (object value, Jsonconfig jsonconfig) {if (value instanceof Date) {String str = new SimpleDateFormat (format). Format ((Date) value); return str;} return value = = null? Null:value.toString ();} Public String GetFormat () {return format;} public void SetFormat (String format) {this.format = format;}}

  

Ps:
public static void Main (string[] args) {//For objects with explicit types of object properties, regardless; But the object has a collection property, because the type is ambiguous, the type is explicit first: String jsonstring = Request.getparameter ("JSON");//increment the type of the collection property in the object and the type of the object property in the object element map Clazzmap = new HashMap ();// Seconditems is a collection attribute in Firstdto clazzmap.put ("Seconditems", Seconddto.class);//thirditems is a collection attribute in Seconddto clazzmap.put ("Thirditems", Thirddto.class); Firstdto firstdto = (firstdto) jsonutil.getdto (jsonstring, Firstdto.class, Clazzmap); }

  

Several methods of Java background parsing JSON

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.