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

JSON API规范中attributes能否为数组?C#反序列化咨询

JSON API规范合规性与C#反序列化问题解答

1. 示例是否符合JSON API规范?

不符合。JSON API规范明确要求resource object的attributes字段必须是对象类型——键为属性名称,值为对应属性内容,不允许使用数组。你提供的示例中attributes是数组结构,违反了这一规范。

2. 非规范结构的C#反序列化处理(JSONAPISerializer)

JSONAPISerializer是严格遵循JSON API规范开发的,默认不支持反序列化这种不符合规范的结构。如果必须处理该格式,可以通过两种变通方式:

  • 先用常规JSON序列化库(如Newtonsoft.Json)反序列化为自定义的兼容模型,再转换为JSONAPISerializer要求的规范模型;
  • 实现自定义转换器,让JSONAPISerializer能识别数组形式的attributes并转换为规范的对象结构。

以下是第一种方式的代码示例:

// 自定义匹配非规范结构的模型
public class NonCompliantResource
{
    public string type { get; set; }
    public string id { get; set; }
    public List<Dictionary<string, string>> attributes { get; set; }
    public ResourceLinks links { get; set; }
}

public class ResourceLinks
{
    public string self { get; set; }
}

public class NonCompliantDocument
{
    public object meta { get; set; }
    public DocumentLinks links { get; set; }
    public JsonApiInfo jsonapi { get; set; }
    public NonCompliantResource data { get; set; }
}

public class DocumentLinks
{
    public string self { get; set; }
}

public class JsonApiInfo
{
    public string version { get; set; }
    public object meta { get; set; }
}

// 反序列化并转换为规范结构
var json = "你的目标JSON字符串";
var nonCompliantDoc = JsonConvert.DeserializeObject<NonCompliantDocument>(json);

// 转换为JSONAPISerializer兼容的规范模型(假设已有规范模型Resource)
var compliantResource = new Resource
{
    Type = nonCompliantDoc.data.type,
    Id = nonCompliantDoc.data.id,
    Attributes = nonCompliantDoc.data.attributes.FirstOrDefault() ?? new Dictionary<string, object>(),
    Links = nonCompliantDoc.data.links
};

注意:上述方案属于临时变通,建议优先要求API输出符合JSON API规范,从根源避免兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:55:18