Th3B0Y
Th3B0Y

Reputation: 994

JSON Doesn't set dictionary

I have the following JSON input from a webserver:

{
    "success":1,
    "return":{
        "45677":{
            "pair":"aaaa",
            "type":"bbbbbbbb",
            "amount":1.00000000,
            "rate":3.00000000,
            "timestamp_created":1342448420,
            "status":0
        }
    }
}

I'm using Newtonsoft JSON.net.

I have the following class:

public class ActiveOrders
    {
        public Dictionary<int, Order> Dictionary { get; private set; }

        public static ActiveOrders ReadFromJObject(JObject o)
        {
            if (o == null) return null;

            return new ActiveOrders
            {
                Dictionary =
                    o.OfType<KeyValuePair<string, JToken>>()
                        .ToDictionary(item => int.Parse(item.Key), item => Order.ReadFromJObject(item.Value as JObject))
            };
        }
    }

It doesn't return null, which means the answers ok, as it is in my other methods. But the result of ActiveOrders.Dictionary is empty.

Here is the class Order:

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

    public static Order ReadFromJObject(JObject o)
    {
        if (o == null) return null;

        return new Order
        {
            Pair = BtcePairHelper.FromString(o.Value<string>("pair")),
            Type = TradeTypeHelper.FromString(o.Value<string>("type")),
            Amount = o.Value<decimal>("amount"),
            Rate = o.Value<decimal>("rate"),
            TimestampCreated = o.Value<UInt32>("timestamp_created"),
            Status = o.Value<int>("status")
        };
    }
}

The types are correct, as are my other classes, they all look the same.

I would like some ideas to make it work. Any advice?

Upvotes: 0

Views: 199

Answers (1)

L.B
L.B

Reputation: 116168

Below code works.....

var obj = JsonConvert.DeserializeObject<ActiveOrders>(json);

public class ActiveOrders
{
    public int success { get; set; }
    public Dictionary<string,Order> @return { get; set; }
}

public class Order
{
    public string pair { get; set; }
    public string type { get; set; }
    public double amount { get; set; }
    public double rate { get; set; }
    public int timestamp_created { get; set; }
    public int status { get; set; }
}

Upvotes: 3

Related Questions