Restsharp类成员Json到C#映射的注释

时间:2017-08-10 11:50:33

标签: c# json annotations deserialization restsharp

我得到了这个json:

 "history": {
        "-Kr6ZcI0_SSeO0tRYGRe": {
            "created_at": 1502291854572,
            "id": "1307a006-d8a0-2f72-30bf-3a04410b8d1a",
            "last_status": "",
            "method_create": "createFlowjob",
            "new_status": "Queued"
        },
        "-Kr6Zci2Ts3ncYnfP2Cq": {
            "created_at": 1502291856297,
            "gateway_id": 127,
            "id": "1307a006-d8a0-2f72-30bf-3a04410b8d1a",
            "last_status": "Queued",
            "method_create": "HTTP_POST - /flowjob/receive",
            "new_status": "Pending"
        },
        "-Kr6Zd11nYnMu2uLK7-1": {
            "created_at": 1502291857577,
            "gateway_id": 127,
            "id": "1307a006-d8a0-2f72-30bf-3a04410b8d1a",
            "last_status": "Pending",
            "method_create": "HTTP_POST - /gateway/processor",
            "new_status": "Running"
        },
        "-Kr6ZlV7eD16nLI4FuGe": {
            "created_at": 1502291892274,
            "gateway_id": 127,
            "id": "1307a006-d8a0-2f72-30bf-3a04410b8d1a",
            "last_status": "Running",
            "method_create": "HTTP_DELETE - /gateway/processor/:job_id",
            "new_status": "Completed"
        }
    }

我想把它映射到像这样的c#类

public class History
    {
        [JsonProperty("somerandomnumberidontknowbefore")]
        [SerializeAs(Name = "somerandomnumberidontknowbefore")]
        [DeserializeAs(Name = "somerandomnumberidontknowbefore")]
        public Dictionary<string,HistoryItem> Items{ get; set; }           
    }

public class HistoryItem
    {

        [JsonProperty("created_at")]
        [SerializeAs(Name = "created_at")]
        [DeserializeAs(Name = "created_at")]
        public int CreatedAt { get; set; }

        [JsonProperty("id")]
        [SerializeAs(Name = "id")]
        [DeserializeAs(Name = "id")]
        public string Id { get; set; }

        [JsonProperty("last_status")]
        [SerializeAs(Name = "last_status")]
        [DeserializeAs(Name = "last_status")]
        public string  LastSTatus { get; set; }

        [JsonProperty("method_create")]
        [SerializeAs(Name = "method_create")]
        [DeserializeAs(Name = "method_create")]
        public string MethodCreate { get; set; }

        [JsonProperty("new_status")]
        [SerializeAs(Name = "new_status")]
        [DeserializeAs(Name = "new_status")]
        public string NewStatus { get; set; }
    }

我的词典永远不会被填满,我也不知道如何正确地将这个json映射到班级。 Json到c#转换器给了我非常奇怪的结果,这没有用。

这里有人知道如何实现一个json密钥的映射,这个密钥总是随机的,在运行时不知道吗?

1 个答案:

答案 0 :(得分:0)

我不知道restsharp,但是使用NewtonSoft你可以使用如下的动态;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

dynamic result = JsonConvert.DeserializeObject<dynamic>(json);

foreach (JProperty x in (JToken)result)
{                
    Console.WriteLine("{0}:{1}", x.Name, x.Value.ToString());            
}