【问题标题】:Constructing C# object for the JSON [duplicate]为 JSON 构建 C# 对象 [重复]
【发布时间】:2018-03-31 11:51:47
【问题描述】:

我正在尝试为我的应用程序中的 JSON 响应创建一个 C# 对象。我有如下 JSON 格式

 {
"@odata.context": "https://example.com/odata/$metadata#REQ",
"value": [
    {
        "Id": 17,
        "Name": "Req"
    }
  ]
 }

我不确定如何为 @odata.context 创建 C# 对象

public class RootObject
    {
        public string @odata.context { get; set; }
        public List<Value> value { get; set; }
    }

它在@odata.context 中抛出错误

【问题讨论】:

  • 你使用的是哪个库?
  • 此任务的自动化可用:json2csharp.com
  • @GeorgPatscheider 这里的问题是c#标识符中不能有特殊字符,通过指定JSON属性名称在给定的答案中解决了这个问题。

标签: c# json json-deserialization


【解决方案1】:

这是因为 C# 中的标识符不能有 @ 符号。您还没有说明您使用的是什么库,但如果是 JSON.NET 那么您可以简单地装饰属性。

public class Root
{
    [JsonProperty("@odata.context")]
    public string OdataContext { get; set; }

    [JsonProperty("value")]
    public List<Value> Value { get; set; }
}

public class Value
{
    [JsonProperty("Id")]
    public long Id { get; set; }

    [JsonProperty("Name")]
    public string Name { get; set; }
}

【讨论】:

  • JSON.NET 不区分大小写。您可以删除所有JsonProperty,只保留[JsonProperty("@odata.context")]
  • 我正在使用 Newtonsoft.Json 我该如何解决这个问题
  • @aloisdg 好点,但它只是作为 OP 关于装饰属性的演示
  • @user4912134 它们是一样的,上面的代码应该适合你。
【解决方案2】:

我会推荐使用Newtonsoft Json.NET

您还可以在文档页面上找到大量示例。这正是您问题的解决方案(我添加了有问题的字段“@odata.context”,以便您了解如何在 JSON 响应和您的类之间进行映射:

https://www.newtonsoft.com/json/help/html/DeserializeObject.htm

public class Account
{
    [JsonProperty("@odata.context")]
    public string myText { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}


string json = @"{
  '@odata.context': 'this is an attribute with an @ in the name.',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin'
  ]
}";

Account account = JsonConvert.DeserializeObject<Account>(json);

Console.WriteLine(account.myText);
// this is an attribute with an @ in the name.

防止在您的属性名称中使用“@”。而是使用JsonProperty。这使您能够将 JsonProperty 映射到您的类字段之一(在这种情况下,它将 JSON 属性 @odata.context 映射到您的类的 myText 属性。

【讨论】:

  • 这个答案与我的有什么不同,特别是因为您后来编辑了您的答案以从我的答案中复制相关信息?您的 JSON 和类甚至无法正确匹配问题...
  • 我想我们是同时发的,所以可能没有区别。我没想到海报使用的是Newstonsoft Json,所以我首先发布了一个完整的反序列化“教程”。我已经在我的第一篇文章中提到了Prevent using "@" for your property namens,但后来添加了 JsonProperty 以获得答案,这几乎是发帖人要求的答案。我不需要复制你的答案!
  • 不,您发布(复制和粘贴)一个完全无效的答案,错过了唯一重要的部分,即物业装饰。您在 10 分钟后对其进行了编辑,以从我的答案中复制相关部分,而您的课程/JSON仍然无效!
  • 不,它不是无效的。在发布之前,我正在 VS 中检查我的代码!你有什么问题?
  • 查看问题中的 JSON 和类,然后查看您的。它甚至远程相同吗?不...我的问题是您的答案既是抄袭又是错误的。由于我们都在审核该网站,因此我在此呼吁您。
猜你喜欢
  • 2020-02-27
  • 1970-01-01
  • 2013-11-28
  • 1970-01-01
  • 2015-05-28
  • 2018-12-01
  • 1970-01-01
  • 2015-05-09
  • 1970-01-01
相关资源
最近更新 更多