Th3B0Y
Th3B0Y

Reputation: 994

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?

Upvotes: 0

Views: 77

Answers (1)

user2160375
user2160375

Reputation:

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>();

Upvotes: 1

Related Questions