一、环境准备:使用maven特性在pom.xml中导入fastjson的依赖包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
二、序列化
package cn.xiaobing.json; import com.alibaba.fastjson.JSONObject; import cn.xiaobing.pojo.ResultJson; public class jsonDemo02 { /**将对象序列化成json * @return jsonString */ public static String entityToJsonString () { //构造器实例化对象 ResultJson resutlJson = new ResultJson("2","登录失败,密码错误!"); //利用fastjson中JSONObject类的toJSONString方法,实现将对象ResultJson转化为jsonString // String jsonString = JSONObject.toJSONString(resutlJson); //如果需要美化输出json格式 String jsonString = JSONObject.toJSONString(resutlJson,true); return jsonString; } public static void main(String[] args) { String jsonString = entityToJsonString(); System.out.println("ResultJson序列化json字符串:"+"\n"+jsonString); } }
三、反序列化
1.提供json字符串如:{"status":"1","message":"登录成功"}
2.创建实体类对象
package cn.xiaobing.pojo; /**创建实体类ResultJson,属性与提供jsonString中的key保持一致 * @author Administrator */ public class ResultJson { private String status; private String message; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public ResultJson() { super(); } public ResultJson(String status, String message) { super(); this.status = status; this.message = message; } @Override public String toString() { return "ResultJson [status=" + status + ", message=" + message + "]"; } }
3.利用fastJson实现json字符串的反序列化
1 package cn.xiaobing.json; 2 3 import java.util.Map; 4 5 import com.alibaba.fastjson.JSONObject; 6 7 import cn.xiaobing.pojo.ResultJson; 8 9 /**利用fastJson实现json字符串的反序列化 10 * @author Administrator 11 */ 12 public class jsonDemo01 { 13 //提供json字符串{"status":"1","message":"登录成功"} 14 static String jsonString = "{\"status\":\"1\",\"message\":\"登录成功\"}"; 15 /** 16 * 利用fastJson实现json字符串反序列化为对象 17 */ 18 public static ResultJson jsonStringToEntity() { 19 20 //创建实体类 resultJson,利用fastjson中JSONObject类的parseObject方法,实现将jsonString转化为对象ResultJson 21 ResultJson resultJson = JSONObject.parseObject(jsonString, ResultJson.class); 22 return resultJson; 23 } 24 /** 25 * 利用fastJson实现json字符串保存Map中 26 */ 27 public static Map<String, String> jsonStringToMapping() { 28 //将json字符串封装到Map 29 Map<String, String> map = (Map<String, String>) JSONObject.parse(jsonString); 30 return map; 31 } 32 public static void main(String[] args) { 33 ResultJson resultJson = jsonStringToEntity(); 34 System.out.println("json转换成对象输出:"+"status:"+resultJson.getStatus()+",message:"+resultJson.getMessage()); 35 Map<String, String> map = jsonStringToMapping(); 36 System.out.println("json转换成Map输出:"+"status:"+map.get("status")+",message:"+map.get("message")); 37 } 38 }
4.未完待续... ...
原文地址:https://www.cnblogs.com/xiaozhaoboke/p/11029695.html
时间: 2024-10-08 14:12:29