首页 > 解决方案 > 我可以映射一个 JSON 元素“@somename”吗?

问题描述

我的目标是带有 winforms 应用程序的 .net framework 4.7。我首先关注这篇文章https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient所以我正在使用 DataContractJsonSerializer。我正在尝试了解返回 JSON 的 REST 接口 -

{"Resource":
    {"@attributes":
        {"name":"Asset",
        "resourceId":"Asset",
        "type":"Resource"
        }
    }
}

我使用 netwonsoft.json 12.0.2 将 JSON 粘贴为类。它忽略“@”字符,并在“资源”类中创建一个“属性”类型的成员“属性”。
当 DataContractJsonSerializer 尝试反序列化 JSON 时,它会跳过 @attribute 元素,我认为是因为它与类名不匹配。

有没有办法将元素 @attributes 映射到我的属性成员/类?

我尝试在 Resource 类的属性成员上添加 [DataMember(Name = "@attributes")] 并在 Attributes 类上添加 [DataContract(Name = "@attributes")] 但仍然似乎跳过了元素(属性资源的成员为空)。

标签: c#jsonwinformsdatacontractjsonserializer

解决方案


是的,使用JsonProperty

public class MyClass
{
    [JsonProperty("@attributes")]
    public string attributes { get; set; }
}

推荐阅读