Conversion between JSON strings and java objects [json-lib] And jsonjson-lib

Source: Internet
Author: User

Conversion between JSON strings and java objects [json-lib] And jsonjson-lib

During development, data is often exchanged with other systems. The data exchange formats include XML and JSON. JSON, as a lightweight data format, is more efficient than xml, XML requires a lot of labels, which undoubtedly occupies network traffic. JSON is doing well in this respect. Let's take a look at the JSON format first,

JSON can be in two formats: Object format and array object,

{"Name": "JSON", "address": "Xicheng District, Beijing", "age": 25} // JSON object Format String

 

[{"Name": "JSON", "address": "Xicheng District, Beijing", "age": 25}] // data object format


From the two formats above, we can see that the only difference between the object format and the array object format is the addition of [] on the basis of the object format. Then let's look at the specific structure, it can be seen that they all appear in the form of key-value pairs, separated by commas (,) in English.

This format is also very popular when data is transmitted between the front end and the back end. The back end returns a json string, and the front end uses JSON in js. the parse () method parses the JSON string into a json object and then traverses it for front-end use.

Next we will go to the topic to introduce the conversion between JSON and JAVA objects in java.

To implement mutual conversion between JSON and java objects, you need to use a third-party jar package. Here, the jar package of json-lib is used, which is.

Json-lib provides several classes to complete this function, such as JSONObject and JSONArray. From the class name, we can see that JSONObject should be converted to the object format, while JSONArray should be converted to an array object (that is, with the [] form.

I. Conversion of common java objects and json strings

Java object -- "string

A java common object refers to a java bean in java, that is, an entity class, such,

Package com.cn. study. day3; public class Student {// name private String name; // age private String age; // address private String address; public String getName () {return name ;} public void setName (String name) {this. name = name;} public String getAge () {return age;} public void setAge (String age) {this. age = age;} public String getAddress () {return address;} public void setAddress (String address) {this. address = address ;}@ Override public String toString () {return "Student [name =" + name + ", age =" + age + ", address = "+ address +"] ";}}


 

The above is a common java entity class of mine. Let's see how json-lib converts it into a string,

Public static void convertObject () {Student stu = new Student (); stu. setName ("JSON"); stu. setAge ("23"); stu. setAddress ("Xicheng District, Beijing"); // 1. Use JSONObject json = JSONObject. fromObject (stu); // 2. Use JSONArray = JSONArray. fromObject (stu); String strJson = json. toString (); String strArray = array. toString (); System. out. println ("strJson:" + strJson); System. out. println ("strArray:" + strArray );}


 

I have defined a Student object class and converted it into a JSON string using JSONObject and JSONArray respectively. The printed result is as follows,

StrJson: {"address": "Xicheng District, Beijing", "age": "23", "name": "JSON"} strArray: [{"address ": "Xicheng District, Beijing", "age": "23", "name": "JSON"}]

From the results, we can see that both methods can convert java objects into JSON strings, but the converted structure is different.

JSON string -- "java object

The preceding explains how to convert a java object to a JSON string. The following describes how to convert a JSON string format to a java object,

First, you need to define two strings of different formats, and use \ to escape double quotation marks,

Public static void jsonStrToJava () {// defines two strings of different formats: String objectStr = "{\" name \ ": \" JSON \ ", \" age \": \ "24 \", \ "address \": \ "Xicheng District, Beijing \"} "; String arrayStr =" [{\ "name \": \ "JSON \", \ "age \": \ "24 \", \ "address \": \ "Xicheng District, Beijing \"}] "; // 1. Use JSONObject jsonObject = JSONObject. fromObject (objectStr); Student stu = (Student) JSONObject. toBean (jsonObject, Student. class); // 2. Use JSONArray jsonArray = JSONArray. fromObject (arrayStr); // obtain the first element of jsonArray, Object o = jsonArray. get (0); JSONObject jsonObject2 = JSONObject. fromObject (o); Student stu2 = (Student) JSONObject. toBean (jsonObject2, Student. class); System. out. println ("stu:" + stu); System. out. println ("stu2:" + stu2 );}

The output is as follows:

Stu: Student [name = JSON, age = 24, address = Xicheng District, Beijing] stu2: Student [name = JSON, age = 24, address = Xicheng District, Beijing]

From the code above, we can see that using JSONObject can easily convert JSON strings into java objects, but using JSONArray is not that easy, because it has the "[]" symbol, therefore, after obtaining the JSONArray object, take the first element of the object, that is, the student deformation we need, and then use JSONObject to easily obtain the object.

Ii. Conversion of list and json strings

List -- "json string

 

Public static void listToJSON () {Student stu = new Student (); stu. setName ("JSON"); stu. setAge ("23"); stu. setAddress ("Haidian District, Beijing"); List <Student> lists = new ArrayList <Student> (); lists. add (stu); // 1. Use JSONObject // JSONObject listObject = JSONObject. fromObject (lists); // 2. Use JSONArray listArray = JSONArray. fromObject (lists); // System. out. println ("listObject:" + listObject. toString (); System. out. println ("listArray:" + listArray. toString ());}

I noted out the JSONObject method. Let's take a look at the previous results,

Exception in thread "main" net.sf.json.JSONException: 'object' is an array. Use JSONArray instead

I am told that there is an exception. By checking the source code, we can see that when using the fromObject method, we will first judge the parameter type. Here we will tell you that the input parameter is of the array type, because the ArrayList is used, let's look at the result after the annotation,

ListArray: [{"address": "Haidian District, Beijing", "age": "23", "name": "JSON"}]

The result is normal.
Json string -- "list

From the above example, we can see that the list object can only be converted to the array object format, so we can see the conversion from the following string to the list,

Public static void jsonToList () {String arrayStr = "[{\" name \ ": \" JSON \ ", \" age \ ": \" 24 \", \ "address \": \ "Xicheng District, Beijing \"}] "; // convert it to list List <Student> list2 = (List <Student>) JSONArray. toList (JSONArray. fromObject (arrayStr), Student. class); for (Student stu: list2) {System. out. println (stu);} // convert it to the array Student [] ss = (Student []) JSONArray. toArray (JSONArray. fromObject (arrayStr), Student. class); for (Student student: ss) {System. out. println (student );}}

Print the result,

Student [name = JSON, age = 24, address = Xicheng District, Beijing] Student [name = JSON, age = 24, address = Xicheng District, Beijing]

Because the string format is in the format of "[]", the JSONArray object is selected here. It has toArray and toList methods available. The former is converted to an array in java, or convert it to list in java. Because there is an object class corresponding here, the generic type (Student. class) to get the converted object.

Iii. Conversion of map and json strings

Map -- "json string

Public static void mapToJSON () {Student stu = new Student (); stu. setName ("JSON"); stu. setAge ("23"); stu. setAddress ("Shanghai, China"); Map <String, Student> map = new HashMap <String, Student> (); map. put ("first", stu); // 1. JSONObject mapObject = JSONObject. fromObject (map); System. out. println ("mapObject" + mapObject. toString (); // 2. JSONArray mapArray = JSONArray. fromObject (map); System. out. println ("mapArray:" + mapArray. toString ());}

Print the result,

MapObject {"first": {"address": "Shanghai, China", "age": "23", "name": "JSON"} mapArray: [{"first": {"address": "Shanghai, China", "age": "23", "name": "JSON"}]

The preceding two formats are printed.

Json string -- "map

JSON strings cannot be directly converted to map objects. To obtain the values corresponding to the keys in the map,

Public static void jsonToMap () {String strObject = "{\" first \ ": {\" address \ ": \" China Shanghai \ ", \" age \": \ "23 \", \ "name \": \ "JSON \"} "; // JSONObject jsonObject = JSONObject. fromObject (strObject); Map map = new HashMap (); map. put ("first", Student. class );
// The toBean method is used. Three parameters are required.
MyBean my = (MyBean) JSONObject. toBean (jsonObject, MyBean. class, map); System. out. println (my. getFirst ());}

Print the result,

Student [name = JSON, age = 23, address = Shanghai, China]

The following is the MyBean code,

package com.cn.study.day4;import java.util.Map;import com.cn.study.day3.Student;public class MyBean {        private Student first;    public Student getFirst() {        return first;    }    public void setFirst(Student first) {        this.first = first;    }    }

The toBean () method is used to pass in three parameters. The first is the JSONObject object, the second is MyBean. class, and the third is a Map object. You can use MyBean to know that this class has a first attribute and its type is Student. It corresponds to the key and Value Type in map, that is, the type of the value corresponding to the key first type.

The content of converting complex JSON strings into java objects will be further described in the next article.

This article mainly describes the conversion of bean, list, map, and JSON in java.

If there are any errors, please note. Thank you!

Welcome to the next 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.