Examples of transformations between JSON and objects and collections

  • 2020-05-27 04:47:39
  • OfStack

Interconversion between JSON strings and java objects [json-lib]

In the development process, it is often necessary to exchange data with other systems. Data exchange formats include XML, JSON, etc. As a lightweight data format, JSON is more efficient than xml. XML needs a lot of tags, which undoubtedly occupies network traffic.

JSON can be in two formats, one for objects and one for array objects,


{"name":"JSON","address":" Xicheng district, Beijing ","age":25}//JSON The object format of the string  

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

As can be seen from the above two formats, the only difference between the object format and array object format is the addition of [] on the basis of the object format. As for the specific structure, it can be seen that both of them are in the form of key-value pairs separated by a comma (,) in the English state.

This format is also popular when data is transferred between the front end and the back end. The back end returns a string in json format. The front end USES the JSON.parse () method in js to parse the JSON string into an json object and then traverses it for the front end to use.

Now let's get down to business and introduce the interchanges between JSON and java objects in JAVA.

To achieve interconversion between JSON and java objects, the third party jar package is needed. Here, the jar package json-lib is used. The download address is: https: / / sourceforge net/projects/json lib/json lib need commons - beanutils - 1.8.0 comes with. jar, commons - collections - 3.2.1. jar, commons lang - 2.5 jar, commons - logging - 1.1.1. jar, ezmorph - 1.0.6. jar5 package of support, You can download it from the Internet by yourself. The download address is no longer posted here.

json-lib provides several classes to do this, for example, JSONObject, JSONArray. As you can see from the name of the class, JSONObject should be converted in object format, while JSONArray should be converted in array objects (that is, with the form []).

1. Interconversion of java ordinary objects and json strings

java object -- "" string

java ordinary objects refer to 1 java bean in java, that is, 1 entity class, such as,


package com.cn.study.day3;

public class Student {
 // The 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 + "]";
 }
 

}

Above is my ordinary java entity class, see how json-lib converts it to a string,


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

  //1 , the use of JSONObject
  JSONObject json = JSONObject.fromObject(stu);
  //2 , the use of 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 Student entity class, and then converted it to JSON string using JSONObject and JSONArray respectively. See the printed result below.


strJson:{"address":" Xicheng district, Beijing ","age":"23","name":"JSON"}
strArray:[{"address":" Xicheng district, Beijing ","age":"23","name":"JSON"}]

It can be seen from the results that both methods can convert java objects into JSON strings, but the structure after conversion is different.

JSON string -- "java object"

The above explains how to convert java object into JSON string. Now let's see how to convert JSON string format into java object.

First, you need to define two strings in different formats. You need to escape the double quotes with \.


public static void jsonStrToJava(){
  // Defines a string in two different formats 
  String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\" Xicheng district, Beijing \"}";
  String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\" Xicheng district, Beijing \"}]";
 
  //1 , the use of JSONObject
  JSONObject jsonObject=JSONObject.fromObject(objectStr);
  Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
  
  //2 , the use of JSONArray
  JSONArray jsonArray=JSONArray.fromObject(arrayStr);
  // To obtain jsonArray The first 1 An element 
  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 printed result is:


stu:Student [name=JSON, age=24, address= Xicheng district, Beijing ]
stu2:Student [name=JSON, age=24, address= Xicheng district, Beijing ]

Can be seen from the above code, the use of JSONObject can easily put JSON format string into java object, but using JSONArray is not so easy, because it has "[]" sign, so we here after getting JSONArray object, take the first element is the one we need student deformation, and then use the JSONObject won easily.

2. Interconversion 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 , the use of JSONObject
  //JSONObject listObject=JSONObject.fromObject(lists);
  //2 , the use of JSONArray
  JSONArray listArray=JSONArray.fromObject(lists);
  
  //System.out.println("listObject:"+listObject.toString());
  System.out.println("listArray:"+listArray.toString());
  
 }

I've just written out the way JSONObject is used, so let's look at the results before the comments,

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

I was told that there was an exception. I found that when using fromObject method, I would judge the parameter type first. Here, I was told that the parameter passed in is 1 array type, because ArrayList is used.


listArray:[{"address":" Haidian district, Beijing ","age":"23","name":"JSON"}]

The result is normal.

json string -- "list

As you can see from the above example, list objects can only be converted into array objects, so let's look at the following string conversion to list.


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

Print the result,


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

Due to the format of the string as "[]" format, so this choice JSONArray this object, it has toArray, toList methods available, the former is converted into an array of java, or into the list java, because there are corresponding to the entity class, so when use specifies the generic type (Student. class), so that you can get into the object.

3. Interconversion of map and json strings

map-- "" json string


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

Print the result,


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

Two forms are printed on it.

json string -- "" map

The JSON string cannot be directly converted to the map object. You need another way to get the corresponding value of the key in map.


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

  // Using the toBean Method, need 3 A parameter  
  MyBean my=(MyBean)JSONObject.toBean(jsonObject, MyBean.class, map);
  System.out.println(my.getFirst());
  
 }

Print the result,


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

Here's the code for MyBean,


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

Using the toBean() method is passed in three parameters, the first is an JSONObject object, the second is an MyBean.class, and the third is an Map object. It can be known from MyBean that there should be 1 attribute of first in this class, and its type is Student, which corresponds to the key and value types in map, that is, first corresponds to the key and value types in first.


Related articles: