Convert data in json format to array format.

1. The function of this method is to convert the data in json format into array format.
2. Suppose there is a Person class with json type data str=str = [{"name":"Zhang San","age":"1"},{"name":"Li Si","age" :"4"}], then

List listt = json.parseArray(str, Person.class); listt can receive str,

First construct two classes:

TestData class:

package com.xzw.test;

public class TestData {

Private String id;

private int arrtibute;

private int sort;

public String getId() {

    return id;

}

public void setId(String id) {

    this.id = id;

}

public int getArrtibute() {

    return arrtibute;

}

public void setArrtibute(int arrtibute) {

    this.arrtibute = arrtibute;

}

public int getSort() {

    return sort;

}

public void setSort(int sort) {

    this.sort = sort;

}   

}

RecVo class:

package com.xzw.test;

import java.util.List;

public class RecVo {

private List<TestData> RecVo;



public List<TestData> getRecVo() {

    return RecVo;

}



public void setRecVo(List<TestData> recVo) {

    RecVo = recVo;

}  

}

Call function code:

   RecVo recVo = new RecVo();

    List<TestData> list = new ArrayList<>();



    TestData testData1 = new TestData();

    testData1.setArrtibute(28);

    testData1.setSort(5);

    testData1.setId("L0000002");

    TestData testData2 = new TestData();

    testData2.setArrtibute(28);

    testData2.setSort(9);

    testData2.setId("L0000012");

    list.add(testData1);

    list.add(testData2);

    recVo.setRecVo(list);



    String str = JSON.toJSONString(recVo);

    System.out.println(str);



    //根据RecVo.class将str解析成对象 

    RecVo toObj = JSON.parseObject(str,  RecVo.class);

    System.out.println(toObj.getRecVo().size());



    String arrJson = JSON.toJSONString(list);

    System.out.println(arrJson);



    //根据TestData.class将arrJson解析成数组

    List<TestData> arrList = JSON.parseArray(arrJson, TestData.class);

    System.out.println(arrList.get(0).getArrtibute());

result:

{“recVo”:[{“arrtibute”:28,”id”:”L0000002”,”sort”:5},{“arrtibute”:28,”id”:”L0000012”,”sort”:9}]}

2

[{“arrtibute”:28,”id”:”L0000002”,”sort”:5},{“arrtibute”:28,”id”:”L0000012”,”sort”:9}]

28

This example is a good example of the role of toJSONString, parseObject, and parseArray.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324548643&siteId=291194637