You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决jsona反序列化JSON API同ID响应时的数据覆盖问题?

问题原因

jsona反序列化时,会以资源的type+id作为唯一标识合并对象。你的两条数据type都是brands、id都是105,会被判定为同一个品牌资源,导致后一条的属性被前一条覆盖——这是因为它遵循JSON API规范:每个type+id组合必须唯一对应一个资源,而你的数据本质是品牌与公司的关联记录,并非独立的品牌资源。

修复方案

提供两种可落地的解决思路:

思路1:调整后端JSON API结构(推荐)

按照JSON API规范拆分资源,把品牌、公司、品牌-公司关联拆成独立实体,用relationships关联:

调整后的数据示例

{
  "meta": {
    "page": {
      "current-page": 1,
      "per-page": 25,
      "from": 1,
      "to": 2,
      "total": 2,
      "last-page": 1
    }
  },
  "data": [
    {
      "type": "brand-company-links",
      "id": "1",
      "attributes": {
        "status": "pending"
      },
      "relationships": {
        "brand": { "data": { "type": "brands", "id": "105" } },
        "company": { "data": { "type": "companies", "id": "1" } }
      }
    },
    {
      "type": "brand-company-links",
      "id": "2",
      "attributes": {
        "status": "approved"
      },
      "relationships": {
        "brand": { "data": { "type": "brands", "id": "105" } },
        "company": { "data": { "type": "companies", "id": "2" } }
      }
    }
  ],
  "included": [
    { "type": "brands", "id": "105", "attributes": { "name": "Brand A" } },
    { "type": "companies", "id": "1", "attributes": { "name": "Company Z" } },
    { "type": "companies", "id": "2", "attributes": { "name": "Company Y" } }
  ]
}

这样jsona反序列化后,每条关联记录都有唯一的type+id,不会被覆盖,还能通过关联关系直接获取品牌和公司的完整信息,符合规范且便于后续扩展。

思路2:前端直接处理原始数据(无需改后端)

如果没法调整后端,就绕过jsona的合并逻辑:

子方案2.1:修改数据标识避免合并

在反序列化前,给每条记录生成唯一的id或修改type,让type+id组合唯一:

import Jsona from 'jsona';

const jsona = new Jsona();
const data = { /* 你的原始数据 */ };

// 用品牌id+公司id拼接成唯一标识
data.data.forEach(item => {
  item.id = `${item.id}-${item.attributes.company_id}`;
  // 可选:修改type更清晰
  // item.type = 'brand-company-links';
});

const result = jsona.deserialize(data);
console.log(result);

子方案2.2:跳过jsona,直接提取数据

如果不需要jsona的资源转换能力,直接从原始数据提取属性即可:

const result = data.data.map(item => ({
  type: item.type,
  id: item.id,
  ...item.attributes
}));
console.log(result);

这样能直接得到两条独立的品牌-公司关联记录,不会被覆盖。


内容的提问来源于stack exchange,提问作者threeFatCat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 13:50:26