UTSJSONObject.parse在uni-app中如果遇到包含对象的数组就会返回null

UTSJSONObject.parse在uni-app中如果遇到包含对象的数组就会返回null

操作步骤:

type Item = {x: number, y: string}
type D = {
list: Item[]
} 
const json: UTSJSONObject = .... // from uni.request
const result = json.parse<D>(); //will be null

预期结果:

const result = json.parse<D>(); //Parse correctly

实际结果:

const result = json.parse<D>(); //will be null

bug描述:

UTSJSONObject.parse方法,如果遇到里面包含对象的数组,就会返回null


更多关于UTSJSONObject.parse在uni-app中如果遇到包含对象的数组就会返回null的实战教程也可以访问 https://www.itying.com/category-93-b0.html

5 回复

提供一下可以说明问题的最简代码 我看一下

更多关于UTSJSONObject.parse在uni-app中如果遇到包含对象的数组就会返回null的实战教程也可以访问 https://www.itying.com/category-93-b0.html


也有可能是嵌套的泛型引起的:
type Item = {x: string};
type Response<D> = {status: string, data: D}
const result = utsJSONObj.parse<Response<Item[]>>(); // result is null
utsJSONObj来自uni.request<UTSJSONObject>…
console.log出来的utsJSONObj的结构和Response<Item[]>是一致的,但是parse返回null

需要发一下完整的最简示例。只有代码片段的话,我这边无法复现问题。

回复 DCloud_Android_DQQ: 随便你们修不修,反正用#ifdef绕过去了

在uni-app中使用UTSJSONObject.parse时遇到包含对象的数组返回null的问题,通常是由于泛型类型定义与运行时JSON结构不匹配导致的。UTS的类型检查较为严格,当JSON实际结构与声明的泛型类型D不完全一致时,解析会失败。

建议检查以下几点:

  1. 确保网络请求返回的JSON数据中list字段确实是对象数组,且每个对象都包含x(number类型)和y(string类型)字段
  2. 验证JSON数据是否完整且格式正确,无额外不可解析字符
  3. 可先用console.log(json)输出原始数据,对比类型定义

临时解决方案:

const rawData = JSON.parse(json.toString()) as any;
const result: D = {
  list: rawData.list.map((item: any) => ({
    x: Number(item.x),
    y: String(item.y)
  }))
};
回到顶部