Various implementation methods for converting Json strings to java objects [json_lib framework, Gson, org. json]

Source: Internet
Author: User

JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy to read and write. It is also easy to parse and generate machines. It is based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition-December 1999. JSON uses a completely language-independent text format, but it also uses a habit similar to the C language family, including C, C ++, C #, Java, JavaScript, Perl, Python, etc ). These features make JSON an ideal data exchange language.

There are many methods to convert JSON strings and java objects! I did some research and experiment on these methods because of my project requirements! I will share my little experience with you. If you have any questions, please correct them!

1. through json_lib to achieve the conversion between json and java objects, the use of JSON-LIB can greatly simplify the operations required to convert JAVA objects to JSON objects, this avoids the trouble and Misoperation caused by manual operations to generate JSON object strings:

Note: To use json_lib, the following jar packages are required:

Json-lib-1.1-jdk15.jar:Http://json-lib.sourceforge.net

Commons-collections-3.2.1.jar

Commons-lang-2.4.jar

Commons-logging-1.1.1.jar

Commons-beanutils-1.8.0.jar

The above commons packages can be found in tomcat/comon/lib;

Ezmorph-1.0.6.jarHttp://ezmorph.sourceforge.net

Morph-1.0.1:Http://morph.sourceforge.net

With the support of these jar packages, you can find the corresponding classes for the json processing methods at ordinary times. paste a code example:

Package util; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import java. util. set; import net. sf. json. JSONArray; import net. sf. json. JSONObject; public class JSONHelper {/*** converts a JSONArray Object to a Map-List Set * @ param jsonArr * @ return */public static Object JsonToList (JSONArray jsonArr) {List <Object> jsonObjList = new ArrayList <Object> (); for (Object obj: jsonArr) {if (obj instanceof JSONArray) {jsonObjList. add (JsonToList (JSONArray) obj);} else if (obj instanceof JSONObject) {jsonObjList. add (JsonToMap (JSONObject) obj);} else {jsonObjList. add (obj) ;}return jsonObjList;}/*** converts a JSONObjec object to a Map-List Set * @ param json * @ return */public static Map <String, object> JsonToMap (JSONObject json) {Map <String, Object> columnValMap = new HashMap <String, Object> (); Set <Object> jsonKeys = json. keySet (); for (Object key: jsonKeys) {Object JsonValObj = json. get (key); if (JsonValObj instanceof JSONArray) {columnValMap. put (String) key, JsonToList (JSONArray) JsonValObj);} else if (key instanceof JSONObject) {columnValMap. put (String) key, JsonToMap (JSONObject) JsonValObj);} else {columnValMap. put (String) key, JsonValObj) ;}return columnValMap;}/*** converts a json object to a map set, this method is used to obtain the list set * @ param obj * @ return */public static List <Object> mapKeys (Object obj) that stores the map set key) {List <Object> keysList = new ArrayList <Object> (); Map <String, Object> columnValMap = new HashMap <String, Object> (); String columnStr = "column "; if (obj instanceof JSONArray) {List <Map <String, Object> jsonObjList = new ArrayList <Map <String, Object> (); jsonObjList = (List <Map <String, object >>) JsonToList (JSONArray) obj); columnValMap = (Map <String, Object>) (jsonObjList. get (0); // the preceding three sentences can be optimized into the following sentence // columnValMap = (Map <String, Object>) (List <Object>) jsonToList (JSONArray) obj )). get (0);} else if (obj instanceof JSONObject) {columnValMap = JsonToMap (JSONObject) obj);} else {keysList. add (obj) ;}for (int I = 0; I <columnValMap. keySet (). size (); I ++) {keysList. add (columnStr + (I + 1);} System. out. println (keysList. size (); return keysList ;}}

2. Google's Gson can be used to process json strings. Google's Gson can easily process encapsulated javaBean strings. However, for unencapsulated json strings, you must find skills to process them.

To use Google's Gson, you also need the support of the jar package. This requires a jar package: Gson. jar

:Http://code.google.com/p/google-gson/downloads/detail? Name=google-gson-2.2.4-release.zip

Example: Convert the json string obtained through js to a Map and List set. The Code is as follows:

Package util; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import com. google. gson. gson; public class JSONHelper {private Gson gson = new Gson ();/*** converts a json object to a map set, this method is used to obtain the list set * @ param obj * @ return */public static List <Object> mapKeys (map <?,?> Map) {List <Object> keysList = new ArrayList <Object> (); String columnStr = "column"; for (int I = 0; I <map. keySet (). size (); I ++) {keysList. add (columnStr + (I + 1);} System. out. println (keysList. size (); return keysList ;} /*** convert the input json String into a List set of map elements * @ param jsonArrStr * @ return */public static List <Map <String, object> jsonObjList (String jsonArrStr) {List <Map <String, Object> jsonObjList = new Arr AyList <Map <String, Object >>(); List <?> JsonList = Test. jsonToList (jsonArrStr); Gson gson = new Gson (); for (Object object: jsonList) {String jsonStr = gson. toJson (object); Map <?, ?> Json = Test. jsonToMap (jsonStr); jsonObjList. add (Map <String, Object>) json);} return jsonObjList ;} /*** resolve the input json string to the List set * @ param jsonStr * @ return */public static List <?> JsonToList (String jsonStr) {List <?> ObjectList = null; Gson gson = new Gson (); java. lang. reflect. Type type = new com. google. gson. reflect. TypeToken <List <?> (){}. GetType (); ObjectList = gson. fromJson (jsonStr, type); return ObjectList;}/*** parses the incoming json string into a Map set * @ param jsonStr * @ return */public static Map <?, ?> JsonToMap (String jsonStr) {Map <?, ?> ObjectMap = null; Gson gson = new Gson (); java. lang. reflect. Type type = new com. google. gson. reflect. TypeToken <Map <?,?> () {}. GetType (); ObjectMap = gson. fromJson (jsonStr, type); return ObjectMap ;}}

3. Use the most lightweight org. json. jar to implement mutual conversion between json strings and java objects

Jar package: org. json. jar

:Www.json.orgOr a third party:Http://kiccp.sinaapp.com/store/info/111

The Code is as follows:

Package util; import java. util. arrayList; import java. util. hashMap; import java. util. iterator; import java. util. list; import java. util. map; import org. json. JSONArray; import org. json. JSONException; import org. json. JSONObject; /*** this class is a tool class for processing json strings ** @ author xiaomeng * @ since 2013-08-27 **/public class JSONHelper {/*** converts a json string to a List set ** @ param jsonArrStr * @ return */public static List <Map <String, Object> jsonObjList (String jsonArrStr) {List <Map <String, Object> jsonList = new ArrayList <Map <String, Object> (); JSONArray jsonArr = null; try {jsonArr = new JSONArray (jsonArrStr); jsonList = (List <Map <String, Object>) JSONHelper. jsonToList (jsonArr);} catch (JSONException e) {System. out. println ("Json String Conversion exception! "); E. printStackTrace ();} return jsonList;}/*** stores the key values of the json object in the set, ing table column ** @ param map * @ return */public static List <String> jsonMapKeysList (Map <?, ?> Map) {List <String> jsonjsonList = new ArrayList <String> (); String columnStr = "column"; for (int I = 0; I <map. keySet (). size (); I ++) {jsonjsonList. add (columnStr + (I + 1);} System. out. println (jsonjsonList. size (); return jsonjsonList ;} /*** convert the passed json array to the List set ** @ param jsonArr * @ return * @ throws JSONException */private static List <?> JsonToList (JSONArray jsonArr) throws JSONException {List <Object> jsonToMapList = new ArrayList <Object> (); for (int I = 0; I <jsonArr. length (); I ++) {Object object = jsonArr. get (I); if (object instanceof JSONArray) {jsonToMapList. add (JSONHelper. jsonToList (JSONArray) object);} else if (object instanceof JSONObject) {jsonToMapList. add (JSONHelper. jsonToMap (JSONObject) object);} else {jsonToMapList. add (object) ;}return jsonToMapList ;} /*** convert the recently passed json object to the Map set ** @ param jsonObj * @ return * @ throws JSONException */@ SuppressWarnings ("unchecked ") private static Map <String, Object> jsonToMap (JSONObject jsonObj) throws JSONException {Map <String, Object> jsonMap = new HashMap <String, Object> (); iterator <String> jsonKeys = jsonObj. keys (); while (jsonKeys. hasNext () {String jsonKey = jsonKeys. next (); Object jsonValObj = jsonObj. get (jsonKey); if (jsonValObj instanceof JSONArray) {jsonMap. put (jsonKey, JSONHelper. jsonToList (JSONArray) jsonValObj);} else if (jsonValObj instanceof JSONObject) {jsonMap. put (jsonKey, JSONHelper. jsonToMap (JSONObject) jsonValObj);} else {jsonMap. put (jsonKey, jsonValObj) ;}return jsonMap ;}}

The conversion methods of the preceding three commonly used json and java objects have their own characteristics. Based on my small experience, I have summarized the advantages and disadvantages as follows for your reference!

1. json_lib json parsing framework

Advantages: various complicated json formats and general requirements for json processing can be achieved

Disadvantage: There are many jar files to be supported, and the jar package version may have some miscellaneous issues.

2. Google Gson's json parsing:

Advantages: 1 ). Google's Gson is a framework for processing conversion between java objects and json objects. It can easily and conveniently convert encapsulated java objects and json-format texts, the conversion between java tool classes is also convenient; 2 ). Compared with the json_lib framework, only one Gson. jar is required, and the number of jar files is small;

Disadvantage: because it is relatively biased towards processing the conversion between java objects and json objects, it only needs a slight transition to process the conversion between json strings and collection classes, is to use reflection to determine the type of the converted java object.

3.org. json framework

Advantage: among the three, the most lightweight and the jar files required by Google Gson are also the least, and it is relatively easy to convert the json string to the java Collection for porn conversion.

Disadvantage: it is difficult for Gson to process conversions between java objects and json objects.

Summary: The three methods for parsing json have their own advantages and disadvantages. You can choose to use them as needed.

This article from the "Dream There is hope" blog, please be sure to keep this source http://mengzhengbin520.blog.51cto.com/7590564/1283361

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.