How to convert Array/List/Map/Object and Json in java

Source: Internet
Author: User
Tags getzip

JSON (JavaScript Object Notation): a lightweight data exchange format. 1. JSON construction has two structures: Object and array. 1. Object: the expanded content of the object represented as "{}" in js. The data structure is {key: value, key: value ,...} the structure of the key-value pair. In the object-oriented language, the key is the object attribute, and the value is the corresponding attribute value, so it is easy to understand that the value method is the object. key, which can be a number, String, array, or object. 2. array: The array is expanded by brackets "[]" in js. The data structure is ["java", "javascript", "vb",...], the value can be obtained using indexes in the same way as in all languages. Field values can be of the following types: Numbers, strings, arrays, and objects. After the object and array structures, you can combine them into complex data structures. II. Specific form 1. Object (1) an object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. (2) Each "name" is followed by a ":" (colon) (3) "," (comma) is used to separate the "name/value" pairs ". Example: an object of a person: {"name": "", "Age": 24} 2. An array is an ordered set of values. (1) An array starts with "[" (left brackets) and ends with "]" (right brackets. (2) Use commas (,) to separate values. Example: A group of students {"student": [{"name": "Xiao Ming", "Age": 23 },{ "name": "", "Age": 24}]} Note: This Json object includes a student array, and the value in the student array is two Json objects. After talking about the basic understanding of the json data structure, I am using the engineering structure diagram of the last demo: The External library referenced above is searched and downloaded online ~ Configdata. json: [javascript] [true, false, true] Address class: [java]/** www.2cto.com * @ Title: Create POJO * @ Description of the Address entity class: TODO (describe what the file does in one sentence) * @ author Potter * @ date 10:16:03 * @ version V1.0 */public class Address {private String street; // Street private String city; // city private int zip; // zip code private String tel; // The first phone number private String telTwo; // public Address () {} public Address (String street, String city, int zip, String tel, String telTwo) {this. street = street; this. city = city; this.zip = zip; this. tel = tel; this. telTwo = telTwo;} public String getStreet () {return street;} public void setStreet (String street) {this. street = street;} public String getCity () {return city;} public void setCity (String city) {this. city = city;} public int getZip () {return zip;} public void setZip (int zip) {this.zip = zip;} public String getTel () {return tel ;} public void setTel (String tel) {this. tel = tel;} public String getTelTwo () {return telTwo;} public void setTelTwo (String telTwo) {this. telTwo = telTwo;} JsonTest class: [java] import java. io. file; import java. io. fileNotFoundException; import java. io. fileReader; import java. io. IOException; import java. util. arrayList; import java. util. linkedHashMap; import java. util. list; import java. util. map; import net. sf. ezmorph. bean. morphDynaBean; import net. sf. json. JSONArray; import net. sf. json. JSONFunction; import net. sf. json. JSONObject; public class JsonTest {public static void main (String args []) {// javaArray and json convert javaArrayAndJsonInterChange (); System. out. println ("-----------------------------------"); // javaList and json convert javaListAndJsonInterChange (); System. out. println ("-----------------------------------"); // convert javaMpa and Json to javaMapAndJsonInterChange (); System. out. println ("inline"); // conversion between Java object and jsonObject to javaObjectAndJsonInterChange ();}/*** mutual conversion between Java array and json */public static void javaArrayAndJsonInterChange () {// convert java to array boolean [] boolArray = new boolean [] {true, false, true}; JSONArray jsonArray = JSONArray. fromObject (boolArray); String s = jsonArray. toString (); System. out. println (s); // obtain the data in the array in json String result = readJson ("configdata"); JSONArray jsonR = JSONArray. fromObject (result); int size = jsonR. size (); for (int I = 0; I <size; I ++) {System. out. println (jsonR. get (I) ;}/ *** alist and json convert each other */public static void javaListAndJsonInterChange () {List list = new ArrayList (); list. add (new Integer (1); list. add (new Boolean (true); list. add (new Character ('J'); list. add (new char [] {'J', 's', 'O', 'n'}); list. add (null); list. add ("json"); list. add (new String [] {"json", "-", "lib"}); // list to convert JSONArray jsArr = JSONArray. fromObject (list); System. out. println (jsArr. toString (4); // string from JSON to JSONArray jsArr = JSONArray. fromObject (jsArr. toString (); // -- read from JSONArray // print: json System. out. println (JSONArray) jsArr. get (6 )). get (0);}/*** mutual conversion between javaMpa and Json */public static void javaMapAndJsonInterChange () {Map map = new LinkedHashMap (); map. put ("integer", new Integer (1); map. put ("boolean", new Boolean (true); map. put ("char", new Character ('J'); map. put ("charArr", new char [] {'J', 's', 'O', 'n'}); // Note: The key name cannot be null, otherwise, net. sf. json. JSONException: // java. lang. nullPointerException: // JSON keys must not be null nor the 'null' string. map. put ("nullAttr", null); map. put ("str", "json"); map. put ("strArr", new String [] {"json", "-", "lib"}); map. put ("jsonFunction", new JSONFunction (new String [] {"I"}, "alert (I)"); map. put ("address", new Address ("P. o box 54534 "," Seattle, WA ", 42452," 561-832-3180 "," 531-133-9098 ")); // map to JSONArray JSONObject jsObj = JSONObject. fromObject (map); System. out. println (jsObj. toString (4); // string from JSON to JSONObject jsObj = JSONObject. fromObject (jsObj. toString (); // The first method: read from JSONObject // print: json System. out. println (jsObj. get ("str"); // print: address. city = Seattle, WA System. out. println ("address. city = "+ (JSONObject) jsObj. get ("address ")). get ("city"); // Method 2: read data from a dynamic Bean. Since it cannot be converted to a specific Bean, it doesn't feel very useful to use MorphDynaBean mdBean = (MorphDynaBean) JSONObject. toBean (jsObj); // print: json System. out. println (mdBean. get ("str"); // print: address. city = Seattle, WA System. out. println ("address. city = "+ (MorphDynaBean) mdBean. get ("address ")). get ("city");}/*** mutual conversion between javaObject and jsonObject */public static void javaObjectAndJsonInterChange () {Address address = new Address ("P. o box 54534 "," Seattle, WA ", 42452," 561-832-3180 "," 531-133-9098 "); // convert object to JSONObject jsObj = JSONObject. fromObject (address); System. out. println (jsObj. toString (4); // convert JsonObject to java Object Address addressResult = (Address) JSONObject. toBean (jsObj, Address. class); System. out. println ("address. city = "+ addressResult. getCity (); System. out. println ("address. street = "+ addressResult. getStreet (); System. out. println ("address. tel = "+ addressResult. getTel (); System. out. println ("address. telTwo = "+ addressResult. getTelTwo (); System. out. println ("address.zip =" + addressResult. getZip ();}/*** read json file * @ param fileName file name, no suffix * @ return */public static String readJson (String fileName) {String result = null; try {File myFile = new File (". /config/"+ fileName + ". json "); FileReader fr = new FileReader (myFile); char [] contents = new char [(int) myFile. length ()]; fr. read (contents, 0, (int) myFile. length (); result = new String (contents); fr. close ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return result ;}}

Related Article

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.