JSON (JavaScript Object Notation) is a lightweight data exchange format, which is very suitable for server-to-JavaScript interaction. Compared with XML, XML is easier to read and write. It is a subset of JavaScript. JSON is in a language-independent text format and can be used in popular languages, such as C # Java C ++ VB. These features make JSON an ideal data exchange language.
I. Json construction structure
1. A collection of name/value pairs ). In different languages, it is understood as an object, record, struct, dictionary, and hash table ), keyed list or associative array ).
2. An ordered list of values ). In most languages, it is understood as an array ).
These are common data structures. In fact, most modern computer languages support them in some form. This makes it possible to exchange a data format between programming languages that are also based on these structures.
II. Specific JSon Representation
1. The object is an unordered set of 'Key/value' pairs. An object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each "name" is followed by a ":" (colon); "," (comma) is used to separate the "name/value" pairs.
2. An array is an ordered set of values. An array starts with "[" (left square brackets) and ends with "]" (right square brackets. Values are separated by commas.
3. The value can be a string, a number, true, false, null, an object, or an array enclosed in double quotation marks ). These structures can be nested.
4. A string is a collection of any number of Unicode characters enclosed by double quotation marks. It is escaped using a backslash.
A character (character) is a separate string (character string ). A string is very similar to a C or Java string.
5. The value (number) is also very similar to the value in C or Java. Remove unused octal and hexadecimal formats. Except for some encoding details.
In javascript
[Javascript] view plaincopyprint?
<Script type = "text/javascript">
Var json = "{name: 'jack', age: 20, city: {address: 'beijing', street: 'chaoyang district '}}";
Alert (json. name );
Alert (json. age );
Alert (json. city. address + json. city. street );
</Script>
You can try it yourself!
Iii. Application of JSon in Java
Let's talk about the code !! Here I use Junit to perform a test. If you do not know how to use shoes, you can learn more. My demo is relatively simple.
[Java]
Package com. jelly. json. test;
Import static org. junit. Assert. assertEquals;
Import java. util. ArrayList;
Import java. util. Date;
Import java. util. HashMap;
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. util. JSONUtils;
Import org. apache. commons. beanutils. PropertyUtils;
Import org. junit. Test;
Import com. jelly. json. entity. MyBean;
Import com. jelly. json. entity. Person;
Import com. jelly. json. entity. Student;
@ SuppressWarnings ("unchecked ")
Public class JsonTest {
Private static void setDataFormat2JAVA (){
// Set the date conversion format
JSONUtils. getMorpherRegistry (). registerMorpher (new DateMorpher (new String [] {"yyyy-MM-dd", "yyyy-MM-dd HH: mm: ss "}));
}
// Convert json to Object
@ Test
Public void testJsonToObj (){
String json = "{id: '000000', name: 'zhangsan', age: 22 }";
Student stu = null;
SetDataFormat2JAVA ();
JSONObject obj = JSONObject. fromObject (json );
Stu = (Student) JSONObject. toBean (obj, Student. class );
System. out. println (stu );
}
// Obtain a java object array from a json Array
@ Test
Public void testJsonArrToArray (){
String jsonStus = "[{id: 1, name: 'jack', age: 20}, {id: 2, name: 'Rose ', age: 20}, {id: 3, name: 'admin', age: 20}] ";
JSONArray array = JSONArray. fromObject (jsonStus );
Student [] stu = new Student [array. size ()];
For (int I = 0; I <array. size (); I ++ ){
JSONObject jsonObject = array. getJSONObject (I );
Stu [I] = (Student) JSONObject. toBean (jsonObject, Student. class );
}
System. out. println (stu [0]);
System. out. println (stu [1]);
System. out. println (stu [2]);
// System. out. println (stu [3]); an error is returned.
}
// Obtain a java set from a JSON Array
@ Test
Public void testJsonArrToList (){
String jsonStus = "[{id: 1, name: 'jack', age: 20}, {id: 2, name: 'Rose ', age: 20}, {id: 3, name: 'admin', age: 20}] ";
JSONArray array = JSONArray. fromObject (jsonStus );
List <Student> stu = new ArrayList <Student> ();
For (int I = 0; I <array. size (); I ++ ){
JSONObject jsonObject = array. getJSONObject (I );
Stu. add (Student) JSONObject. toBean (jsonObject, Student. class ));
}
System. out. println (stu. get (0 ));
System. out. println (stu. get (1 ));
System. out. println (stu. get (2 ));
}
// Obtain the corresponding java array from the json Array
@ Test
Public void testArrayForJson (){
String jsonString = "['Q', 'C', 'D']";
JSONArray jsonArray = JSONArray. fromObject (jsonString );
Object [] strs = jsonArray. toArray ();
System. out. print (strs [0]);
System. out. print (strs [1]);
System. out. print (strs [2]);
}
// Convert string to json
@ Test
Public void testJsonStrToJSON (){
String json = "['json', 'is', 'easy']";
JSONArray jsonArray = JSONArray. fromObject (json );
System. out. println (jsonArray );
// Prints ["json", "is", "easy"]
}
// Map to json
@ Test
Public void testMapToJSON (){
Map map = new HashMap ();
Map. put ("name", "jack ");
Map. put ("bool", Boolean. TRUE );
Map. put ("int", new Integer (1 ));
Map. put ("arr", new String [] {"a", "B "});
Map. put ("func", "function (I) {return this. arr [I];}");
JSONObject jsonObject = JSONObject. fromObject (map );
System. out. println (jsonObject );
}
// Convert a java object to json format
@ Test
Public void testObjToJson (){
JSONObject obj2 = new JSONObject ();
Obj2.put ("phone", "123456 ");
Obj2.put ("zip", "7890 ");
Obj2.put ("contact", obj2 );
System. out. print (obj2 );
}
// Convert a composite bean to json
@ Test
Public void testBeadToJSON (){
MyBean bean = new MyBean ();
Bean. setId ("001 ");
Bean. setName ("bank card ");
Bean. setDate (new Date ());
List cardNum = new ArrayList ();
CardNum. add ("ABC ");
CardNum. add ("ICBC ");
CardNum. add (" ");
CardNum. add (new Person ("test "));
Bean. setCardNum (cardNum );
JSONObject jsonObject = JSONObject. fromObject (bean );
System. out. println (jsonObject );
}
// Convert a general array to JSON
@ Test
Public void testArrayToJSON (){
Boolean [] boolArray = new boolean [] {true, false, true };
JSONArray jsonArray = JSONArray. fromObject (boolArray );
System. out. println (jsonArray );
}
// Convert the Collection object to JSON
@ Test
Public void testListToJSON (){
List list = new ArrayList ();
List. add ("first ");
List. add ("second ");
JSONArray jsonArray = JSONArray. fromObject (list );
System. out. println (jsonArray );
// Prints ["first", "second"]
}
// Convert normal json to an object
@ Test
Public void testJsonToObject () throws Exception {
String json = "{name = \" json \ ", bool: true, int: 1, double: 2.2, func: function (a) {return a ;}, array: [1, 2]} ";
JSONObject jsonObject = JSONObject. fromObject (json );
System. out. println (jsonObject );
Object bean = JSONObject. toBean (jsonObject );
AssertEquals (jsonObject. get ("name"), PropertyUtils. getProperty (bean, "name "));
AssertEquals (jsonObject. get ("bool"), PropertyUtils. getProperty (bean, "bool "));
AssertEquals (jsonObject. get ("int"), PropertyUtils. getProperty (bean, "int "));
AssertEquals (jsonObject. get ("double"), PropertyUtils. getProperty (bean, "double "));
AssertEquals (jsonObject. get ("func"), PropertyUtils. getProperty (bean, "func "));
System. out. println (PropertyUtils. getProperty (bean, "name "));
System. out. println (PropertyUtils. getProperty (bean, "bool "));
System. out. println (PropertyUtils. getProperty (bean, "int "));
System. out. println (PropertyUtils. getProperty (bean, "double "));
System. out. println (PropertyUtils. getProperty (bean, "func "));
System. out. println (PropertyUtils. getProperty (bean, "array "));
List arrayList = (List) JSONArray. toCollection (jsonObject. getJSONArray ("array "));
For (Object object: arrayList) {www.2cto.com
System. out. println (object );
}
}
}
This is the project directory structure