Java如何将String转换成json对象或json数组
一.直接把jar包复制到本地仓库的 net/sf/json-lib/2.4(你对应版本文件夹),jar包名字改成json-lib-2.4.jar,IDEA中重新import下maven项目即可使用JSONObject;二.使用mvninstall命令把jar包安装到本地仓库(其中仓库地址、jar版本、以及下载下来jar的位置 记得改成自己的!下载下来json-lib jar包后,jar包名字都带后
导包:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
<!-- jdk版本 -->
</dependency>
注意:这里会有个问题,无法自动导入依赖
解决方案:
jar包下载地址:Json-lib - Browse Files at SourceForge.net
下载下来json-lib jar包后,jar包名字都带后缀啥jdk15等等; 这时候两种解决方案
一.直接把jar包复制到本地仓库的 net/sf/json-lib/2.4(你对应版本文件夹),jar包名字改成json-lib-2.4.jar,IDEA中重新import下maven项目即可使用JSONObject; 注意,目录下的lastUpdated文件记得删除掉!
二.使用mvn install命令把jar包安装到本地仓库(其中仓库地址、jar版本、以及下载下来jar的位置 记得改成自己的!)
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
这样我们就可以使用JSONObject类了
将String转换成json对象或json数组
注意:json字符串中键的名称要和实体类一致。
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());
}
更多推荐
所有评论(0)