Summary of some of the JSON format and object/string/map/list, such as the Transfer tool class

Source: Internet
Author: User
Tags tojson

Original: Some of the/string/map/list tools for JSON format and object

Source code: Http://www.zuidaima.com/share/1550463691508736.htm

Summed up some of the JSON format and object/string/map/list, such as the mutual transfer tool class, there is need to see, need to introduce Jackson-core-asl-1.7.1.jar, Jackson-jaxrs-1.7.1.jar, Jackson-mapper-asl-1.7.1.jar these three jar packages

Package Com.zuidaima.util.json;import Java.io.inputstream;import Java.io.outputstream;import java.io.Reader;import Java.io.writer;import java.net.url;import java.util.arraylist;import Java.util.date;import java.util.HashMap; Import Java.util.list;import Java.util.map;import Org.codehaus.jackson.jsonnode;import Org.codehaus.jackson.map.deserializationconfig;import Org.codehaus.jackson.map.objectmapper;import Org.codehaus.jackson.map.annotate.jsonserialize;import Org.codehaus.jackson.map.type.typefactory;public Class Jsonutil {private static Objectmapper mapper = new Objectmapper (), static{/** * Ignore extra attributes when deserializing */ Mapper.getdeserializationconfig (). Set (DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, FALSE);/** *                  The null value is ignored, saving space. * @author www.zuidaima.com */Mapper.getserializationconfig (). Setserializationinclusion (JsonSerialize.Inclusion.NO        N_null); /** * Ignore default value wood has changed properties, more space-saving, for the receiver to have the same class * as the Int property initial value is 0, then this property will not be serialized */MApper.getserializationconfig (). Setserializationinclusion (JsonSerialize.Inclusion.NON_DEFAULT);} /** * * @Title: Isjson * @author Kaka * @Description: Determine if jsonstring can be converted to JSON format * @param @param jsonstring * @param @ return * @return Boolean * @throws */public static Boolean Isjson (String jsonstring) {return mapper.canserialize (Ha Shmap.class);}  public static <V> map<string, v> tomap (String content,class<? extends V> Clazz) throws Exception {return Mapper.readvalue (Content, Typefactory.maptype (Hashmap.class,string.class, Clazz));}  public static <V> map<string, v> tomap (InputStream is,class<? extends V> Clazz) throws Exception {return Mapper.readvalue (IS, Typefactory.maptype (Hashmap.class,string.class, Clazz));} public static <V> map<string, v> tomap (Reader is, class<? extends V> Clazz) throws Exception {return Mapp Er.readvalue (IS, Typefactory.maptype (Hashmap.class,string.class, Clazz));} public static <V> map<string, v> Tomap (URL is, class<? extends V> Clazz) throws Exception {return Mapper.readvalue (IS, Typefactory.maptype ( Hashmap.class,string.class, Clazz));} public static <E> list<e> toList (String content, class<? extends E> Clazz) throws Exception {return Jsont Olist (content, clazz);} /** * * @Title: Jsontolist * @author Kaka * @Description: JSON to list, list element type, will be converted to complete such as list<user> * @param @pa Ram <E> * @param @param content * @param @param clazz * @param @return Element type E's list * @param @throws Exception * @return list<e> * @throws */public static <E> list<e> jsontolist (String content,class<? extends e& Gt Clazz) throws Exception {return Mapper.readvalue (content, Typefactory.collectiontype (Arraylist.class, Clazz));} /** * * @Title: Jsontointarray * @author Kaka * @Description: JSON goto array * @param @param content * @param @return * @p Aram @throws Exception * @return integer[] * @throws */public static integer[] Jsontointarray (StRing content) throws Exception {return Jsontoarray (content, integer.class);} public static integer[] Jsontointarray (String content,string key) throws Exception {return Jsontoarray (content, key, Inte Ger.class);} /** * * @Title: Jsontoarray * @author Kaka * @Description: JSON to object array * @param @param <E> * @param @param conte NT * @param @param the object type in the clazz array * @param an array of type @return E, such as user[] * @param @throws Exception * @return e[] * @throw  s */public static <E> e[] Jsontoarray (String content, class<? extends E> Clazz) throws Exception {if (content! = NULL) {return Mapper.readvalue (content, Typefactory.arraytype (Clazz));} Else{return null;}} /** * * @Title: Fromjsontoobject * @author Kaka * @Description: JSON to Java object, compatible with original Util class * @param @param <T> * @par Am @param content * @param @param clazz target type * @param @return * @param @throws Exception * @return T returns an object of type T * @thr oWS */public static <T> T fromjsontoobject (String content,class<? extends t> clAzz) throws Exception {return Jsontoobject (content, clazz);} public static <T> T Jsontoobject (String content, class<? extends T> Clazz) throws Exception {return mapper.read Value (content, clazz);} /** * * @Title: Jsontoobject * @author Kaka * @Description: A jsonstr contains multiple Java objects, taking one of the methods that translates to Java objects * @param @param &l T t> * @param @param content JSON-formatted string * @param @param key to convert the sub-JSON string key * @param @param clazz target type * @param @return return object of type T * @param @throws Exception * @return T * @throws */public static <T> t Jsontoobject (String content, S Tring key,class<? Extends T> clazz) throws Exception {Jsonnode RootNode = mapper.readvalue (content, Jsonnode.class); Jsonnode path = Rootnode.path (key), if (!path.ismissingnode ()) {return Jsontoobject (path.tostring (), clazz);} Else{return null;}} public static Integer GetInt (string content, String key) throws Exception {Jsonnode RootNode = mapper.readvalue (content, J Sonnode.class); Jsonnode path = Rootnode.path (key); if (!path. Ismissingnode ()) {return Jsontoobject (path.tostring (), integer.class);} Else{return null;}}  public static string GetString (string content, String key) throws Exception {Jsonnode RootNode = mapper.readvalue (content, Jsonnode.class); Jsonnode path = Rootnode.path (key), if (!path.ismissingnode ()) {return Jsontoobject (Rootnode.path (key). ToString (), String.class);} Else{return null;}} public static Date GetDate (string content, String key) throws Exception {Jsonnode RootNode = mapper.readvalue (content, Jso Nnode.class); Jsonnode path = Rootnode.path (key), if (!path.ismissingnode ()) {return Jsontoobject (path.tostring (), date.class);} Else{return null;}} /** * A JSONSTR contains multiple Java objects, converting the JSON of the specified key into an array of objects * @param content raw JSON String * @param key to convert the part * @param clazz target type * @retu An array of objects of the RN target type * @throws Exception */public static <E> e[] Jsontoarray (string content, string key,class<? extends E > Clazz) throws Exception {Jsonnode RootNode = mapper.readvalue (content, Jsonnode.class); Jsonnode Path = RootNode. Path (key), if (!path.ismissingnode ()) {return Jsontoarray (Rootnode.path (key). ToString (), clazz);} Else{return null;}} public static integer[] Jsontoarray (string content, String key) throws Exception {Jsonnode RootNode = Mapper.readvalue (con Tent, Jsonnode.class); Jsonnode path = Rootnode.path (key), if (!path.ismissingnode ()) {return Jsontoarray (path.tostring (), integer.class);} Else{return null;}} /** * * @Title: Jsontolist * @author Kaka * @Description: A jsonstr contains multiple Java objects and converts the JSON of the specified key into a list<e> method * @para M @param <E> * @param @param content Raw JSON String * @param @param key to convert that part of JSON * @param @param clazz target type * @param @r The Eturn element is a List * @param of the target type @throws Exception * @return list<e> * @throws */public static <E> list<e > jsontolist (String content, string key,class<? extends E> Clazz) throws Exception {Jsonnode RootNode = mapper.re Advalue (content, Jsonnode.class); Jsonnode path = Rootnode.path (key), if (!path.ismissingnode ()) {return toList (path.tostring (), clazz);} Else{return null;}} /** * * @Title: ToJson * @author Kaka * @Description: Object converted to JSON, known issues a b b b in A,a, if A and B are in one o will not convert normally * @para M @param o the object to convert * @param @return JSON-formatted string * @param @throws Exception * @return String * @throws */public Stati C String ToJson (Object o) throws Exception {return mapper.writevalueasstring (o);} /** * * @Title: ToJson * @author Kaka * @Description: Convert to JSON string to out * @param @param out * @param @param o * @param @ Throws Exception * @return void * @throws */public static void ToJson (OutputStream out, Object o) throws Exception {Mapper.writevalue (out, O);} /** * * @Title: ToJson * @author Kaka * @Description: Convert to a JSON string to writer * @param @param out * @param @param o * @para M @throws Exception * @return void * @throws */public static void ToJson (Writer out, Object o) throws Exception {Ma Pper.writevalue (out, O);} public static String Map2json (map map) throws Exception{return ToJson (map);} /** * * @Title: Formatjson * @author Kaka * @Description: JSON string formatting * @param @param json * @param @param fillstringunit * @param @return * @return String * @throws */public static string Formatjson (String json, string fillstringunit) {if (JSON = = NULL | |         Json.trim (). Length () = = 0) {return null;         } int fixedlenth = 0;         arraylist<string> tokenlist = new arraylist<string> ();             {String jsontemp = json;                 Pre-read while (jsontemp.length () > 0) {String token = GetToken (jsontemp);                 Jsontemp = jsontemp.substring (Token.length ());                 token = Token.trim ();             Tokenlist.add (token); }} for (int i = 0; i < tokenlist.size (); i++) {String token = Tokenli             St.get (i);             int length = Token.getbytes (). length; if (length > Fixedlenth && i < tokenlist.size () -1 && tokenlist.get (i + 1). Equals (":")) {fixedlenth = length;         }} StringBuilder buf = new StringBuilder ();         int count = 0;                          for (int i = 0; i < tokenlist.size (); i++) {String token = tokenlist.get (i);                 if (Token.equals (",")) {buf.append (token);                 Dofill (buf, Count, Fillstringunit);             Continue                 } if (Token.equals (":")) {Buf.append (""). Append (token). Append ("");             Continue                 } if (Token.equals ("{")) {String NextToken = tokenlist.get (i + 1);                     if (Nexttoken.equals ("}")) {i++;                 Buf.append ("{}");                     } else {count++;                     Buf.append (token);                 Dofill (buf, Count, Fillstringunit);          }       Continue                 } if (Token.equals ("}")) {count--;                 Dofill (buf, Count, Fillstringunit);                 Buf.append (token);             Continue                 } if (Token.equals ("[")) {String NextToken = tokenlist.get (i + 1);                     if (Nexttoken.equals ("]")) {i++;                 Buf.append ("[]");                     } else {count++;                     Buf.append (token);                 Dofill (buf, Count, Fillstringunit);             } continue;                 } if (Token.equals ("]")) {count--;                 Dofill (buf, Count, Fillstringunit);                 Buf.append (token);             Continue             } buf.append (token); Left justified if (I < tokenlist.size ()-1 && tokenlist.get (i + 1). Equals (":")) {int Filll Ength = fixedlenth-token.getbytes (). length;  if (Filllength > 0) {for (int j = 0; J < Filllength; J + +) {buf.append ("                     ");     }}}} return Buf.tostring ();         } private static string GetToken (String json) {StringBuilder buf = new StringBuilder ();         Boolean Isinyinhao = false;             while (Json.length () > 0) {String token = json.substring (0, 1);                          JSON = json.substring (1); if (!isinyinhao && token.equals (":") | | Token.equals ("{") | | Token.equals ("}") | | Token.equals ("[") | | Token.equals ("]") | | Token.equals (","))) {if (buf.tostring (). Trim (). Length () = = 0) {buf                 . append (token);             } break;  }            if (token.equals ("\ \")) {buf.append (token);                 Buf.append (json.substring (0, 1));                 JSON = json.substring (1);             Continue                 } if (Token.equals ("\")) {buf.append (token);                 if (Isinyinhao) {break;                     } else {Isinyinhao = true;                 Continue         }} buf.append (token);     } return buf.tostring ();         } private static void Dofill (StringBuilder buf, int count, String fillstringunit) {buf.append ("\ n");         for (int i = 0; i < count; i++) {buf.append (fillstringunit); }     }     }


Summary of some of the JSON format and object/string/map/list, such as the Transfer tool class

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.