Java Learning Summary (20)--json Analysis: Official analysis, Gson analysis, Fastjson analysis,

Source: Internet
Author: User

A Introduction to JSON:
1.JSON (JavaScript Object Notation) is a lightweight data interchange format;
2.JSON data is widely used as one of the main data transmission formats in the current network.
3.JSON can represent the data:
(1) Object: Object expressed as "{}", data structure is {Key:value,key:value,....} The structure of the key-value pairs
For example:
{"Name": "Zhangsan", "Age": 20}
(2) Arrays: arrays are represented as bracketed "[]" contents, data structure is [Value,value,value,.........] or [{key:value,...},{key:value,...}] The single-valued structure
For example:
[{' name ': ' Zhangsan ', ' age ': 20},{' name ': ' Wangwu ', ' Age ': 25}]
That

    {“user”:[{“name”:”zhangsan”,”age”:20},{“name”:”wangwu”,”age”:25}]}

Two. Official parsing of JSON
1. Convert the assembled JavaBean into a JSON data format

2. Convert JSON to JavaBean object

3. Convert the collection to a JSON string

4. Convert a JSON string in array form to a collection object

Example 1 (JSON official parsing):
(1) First introduce the required jar package
(2) Write code:
Conversion Tool Class (contains the method of conversion in 4):

Package Org.json.official;import Java.util.arraylist;import Java.util.collections;import java.util.List;import Org.json.jsonarray;import Org.json.jsonexception;import Org.json.jsonobject;import Org.json.bean.Student;public Class Officejsonutil {//1. Convert Java objects to JSON data format public static String Javatojson () {Student stu = new Student (        1, "Wang Zhaojun", 89.5);        Jsonobject jsonobj = new Jsonobject (stu);    return jsonobj.tostring ();        }//2. Convert JSON to JavaBean object public static Student Jsontojavabean () {Student stu = null;        String jsonstr = "{' id ': 2, ' name ': ' Yang Yuhuan ', ' Score ': 95.6}";            try {jsonobject jsonobj = new Jsonobject (JSONSTR);            int id = jsonobj.optint ("id");            String name = jsonobj.optstring ("name");            Double score = jsonobj.optdouble ("score");        Stu = new Student (ID, name, score);        } catch (Jsonexception e) {e.printstacktrace ();    } return Stu; }//3.   Convert a collection to a JSON string public static String Listtojson () {list<student> List = new arraylist<student> (); Collections.addall (list, new Student (3, "Xi Shi", 93.6), New Student (4, "Marten Cicada", 95.3), New Student (5, "Ping Zhaoyang Princess", 94        .6));        Jsonarray Jsonarr = new Jsonarray (list);    return jsonarr.tostring (); }//4. Convert the JSON string in array form to a collection object public static List<student> Jsonarraytolist () {list<student> List = NE        W arraylist<student> (); String jsonstr = "[{\" score\ ": 93.6,\" name\ ": \" Xi shi \ ", \" id\ ": 3},{\" score\ ": 95.3,\" name\ ": \" Marten cicada \ ", \" id\ ": 4},{\" score\ "        : 94.6,\ "name\": \ "ping Zhaoyang princess \", \ "id\": 5}] ";            try {jsonarray jsonarr=new jsonarray (JSONSTR);                for (int i=0;i<jsonarr.length (); i++) {Jsonobject jsonobj=jsonarr.optjsonobject (i);//To get each object                int Id=jsonobj.optint ("id");                String name=jsonobj.optstring ("name");                Double score=jsonobj.optdouble ("score"); Student StU=new Student (Id,name,score);            List.add (Stu);        }} catch (Jsonexception e) {e.printstacktrace ();    } return list; }}

Test code (Main method):

package org.json.official;import java.util.List;import org.json.bean.Student;public class TestOfJson {    public static void main(String[] args) {        //1.JavaBean转化为JSON数据格式        String jsonStr= OfficeJSONUtil.javaToJSON();        System.out.println("1.JavaBean转化为JSON数据格式:"+jsonStr);        // 2.将JSON转化为JavaBean对象        Student stu=OfficeJSONUtil.jsonToJavaBean();        System.out.println("2.将JSON转化为JavaBean对象:"+stu);        // 3. 把集合转化为JSON字符串        String jsonStr1=OfficeJSONUtil.listToJSON();        System.out.println("3. 把集合转化为JSON字符串:"+jsonStr1);        //4.把数组形式的JSON串转化为集合对象        List<Student> list=OfficeJSONUtil.jsonArrayToList();        System.out.println("4.把数组形式的JSON串转化为集合对象:");        for(Student stu1:list){            System.out.println(stu1);        }    }}

Operation Result:

Java Learning Summary (20)--json Analysis: Official analysis, Gson analysis, Fastjson analysis,

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.