Reprint--------JSON-to-object, the conversion between collections JSON strings and Java objects "Json-lib"

Source: Internet
Author: User
Tags string format


Reprinted--*--*----


In the development process, often need to exchange data with other systems, the format of data exchange is XML, JSON, etc., JSON as a lightweight data format than XML efficiency, XML needs a lot of tags, which undoubtedly occupy the network traffic, JSON is doing well in this respect, Let's look at the JSON format below,



JSON can be in two formats, one in object format and the other as an array object.

{"name": "JSON", "address": "Beijing Xicheng District", "age": 25} // JSON object format string
 

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

From the above two formats, it can be seen that the only difference between the object format and the array object format is the addition of [] on the basis of the object format. Looking at the specific structure, it can be seen that they appear in the form of key-value pairs. , Separated by a comma (,) in English.

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

Let's get into the topic and introduce the conversion between JSON and java objects in JAVA.

To achieve the conversion between JSON and java objects, you need to use a third-party jar package, here use the json-lib jar package: https://sourceforge.net/projects/json-lib/, json-lib needs Commons-beanutils-1.8.0.jar, commons-collections-3.2.1.jar, commons-lang-2.5.jar, commons-logging-1.1.1.jar, ezmorph-1.0.6.jar support in five packages , You can download it from the Internet, and it will not be posted here.

json-lib provides several classes to accomplish this function, for example, JSONObject, JSONArray. It can be seen from the name of the class that JSONObject should be converted to an object format, and JSONArray should be converted to an array object (that is, with [] form).

1. Conversion between java common objects and json strings

  java object-"" string

Java ordinary object refers to a java bean in java, that is, an entity class, such as,

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 one of my ordinary java entity classes, see how json-lib converts it to string form,

public static void convertObject () {
        
        Student stu = new Student ();
        stu.setName ("JSON");
        stu.setAge ("23");
        stu.setAddress ("Beijing Xicheng District");

        // 1, use JSONObject
        JSONObject json = JSONObject.fromObject (stu);
        // 2, use JSONArray
        JSONArray array = JSONArray.fromObject (stu);
        
        String strJson = json.toString ();
        String strArray = array.toString ();
        
        System.out.println ("strJson:" + strJson);
        System.out.println ("strArray:" + strArray);
    }

 

I defined an entity class of Student, and then used two methods to convert JSONObject and JSONArray into JSON string, see the printed result below,

strJson: {"address": "Beijing Xicheng District", "age": "23", "name": "JSON"}
strArray: [{"address": "Beijing Xicheng District", "age": "23", "name": "JSON"}]
It can be seen from the results that both methods can convert java objects to JSON strings, but the structure after conversion is different.

  JSON string-"" java object

The above explains how to convert a java object to a JSON string. Let's see how to convert a JSON string format to a java object.

First, you need to define two different formats of strings, you need to use \ to escape double quotes,

public static void jsonStrToJava () {
        // Define two strings in different formats
        String objectStr = "{\" name \ ": \" JSON \ ", \" age \ ": \" 24 \ ", \" address \ ": \" Xicheng District of Beijing \ "}";
        String arrayStr = "[{\" name \ ": \" JSON \ ", \" age \ ": \" 24 \ ", \" address \ ": \" Xicheng District of Beijing \ "}]";
    
        // 1, use JSONObject
        JSONObject jsonObject = JSONObject.fromObject (objectStr);
        Student stu = (Student) JSONObject.toBean (jsonObject, Student.class);
        
        // 2, use JSONArray
        JSONArray jsonArray = JSONArray.fromObject (arrayStr);
        // Get 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 print result is:

stu: Student [name = JSON, age = 24, address = Xicheng District, Beijing]
stu2: Student [name = JSON, age = 24, address = Xicheng District, Beijing]
As can be seen from the above code, using JSONObject can easily convert a JSON format string into a java object, but using JSONArray is not so easy, because it has the "[]" symbol, so we have obtained JSONArray here After the object, take the first element which is the deformation of a student we need, and then use JSONObject to easily get it.

Second, the conversion between list and json strings

list-》》 json string

 

public static void listToJSON () {
        Student stu = new Student ();
        stu.setName ("JSON");
        stu.setAge ("23");
        stu.setAddress ("Beijing Haidian District");
        List <Student> lists = new ArrayList <Student> ();
        lists.add (stu);
        // 1, use JSONObject
        // JSONObject listObject = JSONObject.fromObject (lists);
        // 2, use JSONArray
        JSONArray listArray = JSONArray.fromObject (lists);
        
        //System.out.println("listObject: "+ listObject.toString ());
        System.out.println ("listArray:" + listArray.toString ());
        
    }
I commented out the way of using JSONObject, let's look at the result before the annotation first,

Exception in thread "main" net.sf.json.JSONException: ‘object‘ is an array. Use JSONArray instead
Tell me that there is an exception. By looking at the source code, it is found that the parameter type will be judged first when using the fromObject method. Here we are told that the incoming parameter is an array type, because the ArrayList used. the result of,

listArray: [{"address": "Beijing Haidian District", "age": "23", "name": "JSON"}]
This result is normal.
json string-》》 list

It can be seen from the above example that the objects of list can only be converted into the format of array objects, then we see the conversion of the following string to list,

public static void jsonToList () {
        String arrayStr = "[{\" name \ ": \" JSON \ ", \" age \ ": \" 24 \ ", \" address \ ": \" Xicheng District of Beijing \ "}]";
        // Convert to list
                List <Student> list2 = (List <Student>) JSONArray.toList (JSONArray.fromObject (arrayStr), Student.class);
                
                for (Student stu: list2) {
                    System.out.println (stu);
                }
                // Convert to 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]
Since the format of the string is the format with "[]", so here select the JSONArray object, it has toArray and toList methods available, the former is converted into an array in java, or into a list in java There is an entity class for correspondence, so the generic type (Student.class) is specified when used, so that you can get the converted object.

Three, map and json string conversion

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
        JSONObject mapObject = JSONObject.fromObject (map);
        System.out.println ("mapObject" + mapObject.toString ());
        
        // 2, JSONArray
        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"}}]
Two forms are printed above.

json string-》》 map

The JSON string cannot be directly converted into a map object. To obtain the value corresponding to the key in the map, another method is required.

public static void jsonToMap () {
        String strObject = "{\" first \ ": {\" address \ ": \" Shanghai, China \ ", \" age \ ": \" 23 \ ", \" name \ ": \" JSON \ "}} ";
        
        // JSONObject
        JSONObject jsonObject = JSONObject.fromObject (strObject);
        Map map = new HashMap ();
        map.put ("first", Student.class);

        // The toBean method is used, which requires three parameters
        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]
Below is the code of MyBean,

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;
    }

    

}
Use toBean () method is passed three parameters, the first is a JSONObject object, the second is MyBean.class, the third is a Map object. Through MyBean, you can know that there is a first attribute in this class, and its type is Student, which corresponds to the key and value type in the map, that is, the first corresponds to the key and the first type corresponds to the value type.

Reprinted -------- Conversion between JSON and objects and collections JSON string and java objects [json-lib]

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.