JSON's Learning Notes

Source: Internet
Author: User

JSON is relatively simple, so start with JSON first.

A name for the JSON:

The full name of JSON is JavaScript Object notation, the Chinese name is the JS objects notation.

JSON definition: JSON is a lightweight data interchange format with good readability and fast writing features. , you can exchange data between different platforms. JSON uses a high-compatibility text format, and also has a similar behavior to the C language system. --json.org

Example and structure of two JSON:

A simple JSON instance:

{"Employees": [{"FirstName": "Bill", "LastName": "Gates"},{"FirstName": "George", "LastName": "Bush"},{"FirstName": " Thomas "," LastName ":" Carter "}]}
The analysis of this example is as follows:

(1) The object in JSON and JS is very similar, it is used as the boundary with a {}, and the array is represented by [].

(2) JSON contains content that is in the form of a key-value pair (Key/value), unordered.

(3) JSON has a self-describing feature.

(4) Multiple properties of JSON are separated by commas, and the last one does not need commas.

Syntax rules for three JSON:

JSON syntax is a subset of the JavaScript object notation syntax.

    • Data in name/value pairs
    • Data is separated by commas
    • Curly braces Save Object
    • Square brackets Save Array

The four JSON values:

The JSON value can be:

    • Number (integer or floating point)
    • String (in double quotes)
    • Logical value (TRUE or FALSE)
    • Array (in square brackets)
    • Object (in curly braces)
    • Null

Five JSON converted to JS object:

Create a JavaScript string that contains the JSON syntax:

var txt = ' {' Employees ': [' + ' {' firstName ': ' Bill ', ' lastName ': ' Gates '}, ' + ' {' firstName ': ' George ', ' lastName ': ' Bush ' }, ' + ' {"FirstName": "Thomas", "LastName": "Carter"}]} ';

Because JSON syntax is a subset of JavaScript syntax, the JavaScript function eval () can be used to convert JSON text to JavaScript objects.

The eval () function uses the JavaScript compiler to parse the JSON text and then generate the JavaScript object. You must enclose the text in parentheses in order to avoid syntax errors:

var obj = eval ("(" + txt + ")");


Six JSON applications in 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 Date conversion format
Jsonutils.getmorpherregistry (). Registermorpher (New Datemorpher (new string[] {"Yyyy-mm-dd", "Yyyy-mm-dd HH:mm:ss"})) ;
}

JSON turns into object
@Test
public void Testjsontoobj () {
String JSON = "{id: ' 1001 ', Name: ' Zhang San ', age:22}";
Student stu = null;
Setdataformat2java ();
Jsonobject obj = Jsonobject.fromobject (JSON);
Stu = (Student) jsonobject.tobean (obj, student.class);
System.out.println (Stu);
}

Get an array of Java objects 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]);
}

Get a Java collection 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));
}
Get 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]);
}

String into JSON
@Test
public void Testjsonstrtojson () {
String json = "[' json ', ' is ', ' easy ']";
Jsonarray Jsonarray = Jsonarray.fromobject (JSON);
System.out.println (Jsonarray);
Prints ["JSON", "is", "easy"]
}

Map into 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);
}

Java objects converted 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);
}

Compound type Bean turns into 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 ("CCB");
Cardnum.add (New person ("test"));

Bean.setcardnum (Cardnum);

Jsonobject jsonobject = Jsonobject.fromobject (bean);
System.out.println (Jsonobject);

}

General arrays converted to JSON
@Test
public void Testarraytojson () {
boolean[] Boolarray = new Boolean[]{true,false,true};
Jsonarray Jsonarray = Jsonarray.fromobject (Boolarray);
System.out.println (Jsonarray);
}

Collection objects into 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"]
}

Normal types of JSON are converted into objects
@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) {
System.out.println (object);
}

}

}



JSON's Learning Notes

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.