Json字符串格式化转成java实体类
程序员文章站
2022-03-26 16:51:11
问题描述:最近遇到一个问题,实体类对象被转成json字符串后,发送到消息队列时,该字符串中的双引号被转译,如下:"{\"messageId\":\"ab3f9fcfe9c9432496dc6304e4085213\",\"result\":{\"key1\":1,\"key2\":2}}"目标本文实现将实体类转成json字符串,再讲json字符串解析封装成实体类对象的过程。package test;import com.alibaba.fastjson.JSON;import com.a...
问题描述:
最近遇到一个问题,实体类对象被转成json字符串后,发送到消息队列时,该字符串中的双引号被转意,转意后的字符串如何转成java对象呢?被转意后的字符串如下:
"{\"messageId\":\"ab3f9fcfe9c9432496dc6304e4085213\",\"result\":{\"key1\":1,\"key2\":2}}"
目标
本文实现将实体类转成json字符串,再讲json字符串解析封装成实体类对象的过程。
package test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import entity.MqInfo;
import java.util.HashMap;
import java.util.Map;
public class TempTest {
public static void main(String[] args) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("k1",1);
map.put("k2",2);
Map<String,Object> message = new HashMap<String,Object>();
message.put("result",map);
//封装消息
MqInfo mqInfo = new MqInfo("5e9bdca610b8404f83597f18172d4832",message);
//将消息转成json串
String jsonStr = JSONObject.toJSONString(mqInfo);
//json解析,注意此处必须转成 JSONObject,后面才可以转成java对象
JSONObject parse = JSONObject.parseObject(jsonStr);
MqInfo mqInfo1 = JSON.toJavaObject(parse, MqInfo.class);
System.out.println(parse);
System.out.println(mqInfo1);
}
}
package entity;
import java.util.Map;
public class MqInfo {
private String messageId;
private Map<String,Object> result;
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public Map<String, Object> getResult() {
return result;
}
public void setResult(Map<String, Object> result) {
this.result = result;
}
public MqInfo() {
}
public MqInfo(String messageId, Map<String, Object> result) {
this.messageId = messageId;
this.result = result;
}
@Override
public String toString() {
return "MqInfo{" +
"messageId=" + messageId +
", result=" + result +
'}';
}
}
后台输出结果
{"result":{"result":{"k1":1,"k2":2}},"messageId":"5e9bdca610b8404f83597f18172d4832"}
MqInfo{messageId=5e9bdca610b8404f83597f18172d4832, result={result={"k1":1,"k2":2}}}
本文地址:https://blog.csdn.net/zxjdC/article/details/110225516