2

This is my incoming JSON packet:

{
   "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"
   ]
}

How can I de-seriazlie the $ts field? Since I cannot use the $ filed in front of property name, which way should I choose to move forward?

This is my model to deserialize:

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

1 回答 1

4

You could try to use the following classes:

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; }
}

Essentially we have decorated the properties with the attribute called JsonProperty passing to its constructor the corresponding name of the keys in the JSON file. Doing so, we can use whatever names we want our objects to have, whereas the JSON file may contains keys whose names start with invalid characters for starting the name of a variable in C#.

The above classes can be autogenerated with using a tool like this one.

于 2019-12-16T14:58:59.023 回答