JSONObject转换异常:expect ‘‘ at 0, actual =

一、传参示例

@Data
public class TbPstData
{
    
    
	private JSONArray sectionParam;
}
 //实际传参:
"sectionParam": [
        {
    
    
            "跨距": 200,
            "延迟时间": -32.0,
            "接收高度": 1.8,
            "首声时的索引值": 60,
            "首波峰的索引值": 67,
            "声时": 0.0,
            "声速": 0.0,
            "波幅": 58.12,
            "主频": 97.65625,
            "PSD": 0.0 
        }
    ]

二、问题描述

//获取数组对象中的每一个值
JSONArray jsonArray = tbPstData.getSectionParam();
System.out.println(jsonArray);
String str = jsonArray.getString(0);
System.out.println(str);
System.out.println(JSONObject.parseObject(str).get("跨距"));
//打印结果如下
[{
    
    "跨距":200,"延迟时间":-32.0,"接收高度":1.8,"首声时的索引值":60,"首波峰的索引值":67,"声时":0.0,"声速":0.0,"波幅":58.12,"主频":97.65625,"PSD":0.0}]
{
    
    跨距=200, 延迟时间=-32.0, 接收高度=1.8, 首声时的索引值=60, 首波峰的索引值=67, 声时=0.0, 声速=0.0, 波幅=58.12, 主频=97.65625, PSD=0.0}
2022-09-22 10:41:17.757 ERROR 15192 --- [0.0-9526-exec-1] c.y.f.exception.GlobalExceptionHandler   : 请求地址'/cs/map',发生未知异常.

com.alibaba.fastjson.JSONException: expect ':' at 0, actual =

报错了:expect ':' at 0, actual =

查看打印数据发现,数据格式从
“跨距”: 200 => 跨距=200
已经不是对象格式的数据了,获取当然得出问题

三、解决办法

System.out.println(tbPstData.getSectionParam());
String str = tbPstData.getSectionParam().toJSONString();
JSONArray sectionDataArray = JSONArray.parseArray(str);
JSONObject currentSectionData = JSONObject.parseObject(sectionDataArray.getString(0));
System.out.println(currentSectionData);
System.out.println(currentSectionData.get("跨距"));
[{
    
    "跨距":200,"延迟时间":-32.0,"接收高度":1.8,"首声时的索引值":60,"首波峰的索引值":67,"声时":0.0,"声速":0.0,"波幅":58.12,"主频":97.65625,"PSD":0.0}]
{
    
    "PSD":0.0,"跨距":200,"延迟时间":-32.0,"声速":0.0,"接收高度":1.8,"首声时的索引值":60,"主频":97.65625,"首波峰的索引值":67,"声时":0.0,"波幅":58.12}
200

先将获取到的JSONArray转成json字符串,再去解析就可以了。暂时不知道原因为何,有懂的大佬可以评论解释下。

猜你喜欢

转载自blog.csdn.net/LuoHuaX/article/details/126987615