简体   繁体   中英

Deserializing JSON to Dictionary

I tried finding a solution here and couldn't so far.

I have the following JSON string:

{
    "success": 1,
    "return": {
        "361683776": {
            "pair": "mypair",
            "type": "mytype",
            "amount": 0.1,
            "rate": 100,
            "timestamp_created": 1410085980,
            "status": 0
         }
     }
}

My DTOs are

public class DtoActiveOrders
{
    public Dictionary<int, DtoOrder> List { get; set; }
}

public class DtoOrder
{
    public Pair Pair { get; set; }
    public TradeType Type { get; set; }
    public decimal Amount { get; set; }
    public decimal Rate { get; set; }
    public UInt32 TimestampCreated { get; set; }
    public int Status { get; set; }
}

I'm trying to deserialize it with

jObject["return"].ToObject<DtoActiveOrders>();

But my issue is that the JSON string will have Order Numbers in return, so that I can't map it. I want to map it in a way that My DtoActiveOrders.List contains value keys "361683776",.

Any idea on how to do that?

You can do the following:

var model = new DtoActiveOrders
                {
                    List =
                        jObject["return"].ToObject<Dictionary<int, DtoOrder>>()
                };

The other way:

public class DtoActiveOrders
{
    [JsonProperty("return")]
    public Dictionary<int, DtoOrder> List { get; set; }
}

then:

var model = jObject.ToObject<DtoActiveOrders>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM