How Java converts String to json object or json array

Guide package:

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
    <!-- jdk版本 -->
</dependency>

Note: There will be a problem here, the dependencies cannot be imported automatically 

solution:

Jar package download address: Json-lib - Browse Files at SourceForge.net

After downloading the json-lib jar package, the name of the jar package has a suffix of jdk15, etc.; at this time, there are two solutions  

      1. Copy the jar package directly to the net/sf/json-lib/2.4 of the local warehouse (your corresponding version folder), change the name of the jar package to json-lib-2.4.jar, and re-import the maven project in IDEA Use JSONObject; Note, remember to delete the lastUpdated file in the directory!

      2. Use the mvn install command to install the jar package to the local warehouse (the warehouse address, jar version, and the location of the downloaded jar should be changed to your own!)

mvn install:install-file  -DgroupId=net.sf.json-lib -DartifactId=json-lib  -Dversion=2.4 -Dpackaging=jar -Dfile=D:\firefoxDownload\Redhat6.8\json-lib-2.4-jdk15.jar

This way we can use the JSONObject class

Convert String to json object or json array

Note: The name of the key in the json string should be consistent with the entity class.

 String datajson =
            "[" +
                "{" +
                    "'aliasName':'Taurus-49999787'," +
                    "'ftpPort':16602," +
                    "'hasPassWord':false," +
                    "'height':1080," +
                    "'ignoreTime':0," +
                    "'ip':'172.16.9.205'," +
                    "'key':'novaStar'," +
                    "'logined':false," +
                    "'loginedUsernames':[" +
                        "''" +
                    "]," +
                    "'password':''," +
                    "'platform':'rk312x'," +
                    "'privacy':true," +
                    "'productName':'TC300'," +
                    "'sn':'BZSA07194A0049999787'," +
                    "'syssetFtpPort':16604," +
                    "'syssetTcpPort':16605," +
                    "'tcpPort':16603," +
                    "'terminalState':5," +
                    "'username':[" +
                    "]," +
                    "'width':1920" +
                "}," +
                "{....}"+
            "]";
JSONArray jsonArray = JSONArray.parseArray(datajson);
for(int i=0; i<jsonArray.size(); i++) {
    JSONObject object = jsonArray.getJSONObject(i);
    Entity entity = JSONObject.parseObject(object.toJSONString() , Entity.class);// 将string类型直接封装成对象
    System.out.println(entity.toString());
}

Guess you like

Origin blog.csdn.net/gp_911014/article/details/132234724