一:maven依赖包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
二:Java对象转JSON字符串
Info info = new Info(1) ;
String jsonString = JSONObject.toJSONString( info );
System.out.println(jsonString);
三:JSON字符串转JSON对象
String jsonString = "{\"id\":123}";
JSONObject jsonObject = JSONObject.parseObject(jsonString);
Object id = jsonObject.getString("id");
四:JSON字符串转Java对象
String jsonString = "{\"id\":123}";
Info info = JSONObject.parseObject(jsonString, Info.class);
System.out.println( clazz.toString() );
五:JSON对象转Java对象
String jsonString = "{\"id\":123,\"name\":\"林风\",\"infos\":[{\"id\":10,\"desc\":\"小阴间\"},{\"id\":10,\"desc\":\"阳间\"}]}\n";
JSONObject jsonObject = JSONObject.parseObject(jsonString);
System.out.println(jsonObject.getString("name"));
//林风
//林风到过的地方转数组
JSONArray jsonArray = jsonObject.getJSONArray("infos");
List<Info> students = jsonArray.toJavaList(Info.class);
六:json字符串转List
String infoListStr = "[{\"id\":10,\"desc\":\"小阴间\"},{\"id\":10,\"desc\":\"阳间\"}]";
List<Info> students = JSONObject.parseArray( infoListStr, Info.class );
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/160867.html