【问题标题】:DeSerialize JSON with variable having a $ sign使用具有 $ 符号的变量反序列化 JSON
【发布时间】:2020-04-09 01:32:05
【问题描述】:

这是我传入的 JSON 数据包:

{
   "schema":{
      "rid":0,
      "$esn":"eventhub1",
      "properties":[
         {
            "name":"deviceId",
            "type":"String"
         },
         {
            "name":"product",
            "type":"String"
         },
         {
            "name":"data.Temperature",
            "type":"Double"
         },
         {
            "name":"data.Humidity",
            "type":"Double"
         },
         {
            "name":"Diagnostic-Id",
            "type":"String"
         }
      ]
   },
   "$ts":"2019-12-16T14:34:10.159Z",
   "values":[
      "xxxx",
      "testProduct",
      27.399,
      15.247,
      "xxxxxx"
   ]
}

如何对 $ts 字段进行反序列化?由于我不能使用属性名前面的 $ 字段,我应该选择哪种方式前进?

这是我要反序列化的模型:

public class Event
    {
        public Schema schema { get; set; }
        public List<object> values { get; set; }
        public int? schemaRid { get; set; }
        //public DateTime $ts { get; set; }
    }

【问题讨论】:

  • 您使用的是 JSON.NET 吗?在这种情况下,请查看 JsonProperty 属性。
  • 您可以尝试将 [JsonProperty("$esn")] 属性添加到 Schema 类中的相应属性。

标签: c# asp.net json jsonconvert


【解决方案1】:

您可以尝试使用以下类:

public class Property
{

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

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

public class Schema
{

    [JsonProperty("rid")]
    public int Rid { get; set; }

    [JsonProperty("$esn")]
    public string Esn { get; set; }

    [JsonProperty("properties")]
    public IList<Property> Properties { get; set; }
}

public class Example
{

    [JsonProperty("schema")]
    public Schema Schema { get; set; }

    [JsonProperty("$ts")]
    public DateTime Ts { get; set; }

    [JsonProperty("values")]
    public IList<object> Values { get; set; }
}

本质上,我们使用名为JsonProperty 的属性修饰了属性,将JSON 文件中键的相应名称传递给其构造函数。这样做,我们可以使用我们希望我们的对象具有的任何名称,而 JSON 文件可能包含名称以无效字符开头的键,用于在 C# 中启动变量的名称。

上述类可以使用one 之类的工具自动生成。

【讨论】:

  • 这是 VS 中的一个简洁扩展:marketplace.visualstudio.com/…
  • @JoelWiklund 确实如此。 Visual Studio 也为您提供了这样的功能。但是,我已经使用过几次我提到的工具,这是我在类似情况下想到的第一个 :)
猜你喜欢
  • 1970-01-01
  • 2020-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多