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

I. JSON construction has two structures: objects and arrays.

1. Object: the expanded content 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: indicates a person's object: {"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...

Supplement: Online JSON validation formatting tool: http://www.bejson.com/go.php? U = http://www.bejson.com/index.php

3. The last demo

My project structure: the external library referenced above is searched and downloaded online ~

Configdata. JSON:

[    true,    false,    true]

Address class:

/*** @ Title: Create the pojo of the address object class * @ Description: Todo (describe what the file is doing 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; // The second phone number public address () {} Public Address (string Street, string city, int zip, string Tel, string teltwo) {This. street = Street; this. city = cityw.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) unzip 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:

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. 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 = 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 jsonarrayjsonarray jsarr = jsonarray. fromobject (list); system. out. println (jsarr. tostring (4); // string from JSON to jsonarrayjsarr = jsonarray. fromobject (jsarr. tostring (); // -- read from jsonarray // print: jsonsystem. out. println (jsonarray) jsarr. get (6 )). get (0);}/*** mutual conversion between javampa and JSON */public static void javamapandjsoninterchange () {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 jsonarrayjsonobject jsobj = jsonobject. fromobject (MAP); system. out. println (jsobj. tostring (4); // string from JSON to jsonobjectjsobj = jsonobject. fromobject (jsobj. tostring (); // The first method: read from jsonobject // print: jsonsystem. 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: jsonsystem. 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 = new address ("P. o box 54534 "," Seattle, wa ", 42452," 561-832-3180 "," 531-133-9098 "); // convert object to jsonobjectjsonobject jsobj = jsonobject. fromobject (Address); system. out. println (jsobj. tostring (4); // convert jsonobject to Java objectaddress 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 ;}}

Haha ~ I didn't expect it to be quite simple !!!

 

See the article:

Http://jiangzhengjun.iteye.com/blog/463769

Http://blog.csdn.net/chenzhehui/article/details/4067482

Http://baike.baidu.com/view/136475.htm

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.