2013-12-17 29 views
0

我有一個Web服務器以下JSON輸入:JSON不設置字典

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

我使用Newtonsoft JSON.net。

我有下面的類:

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

它沒有返回null,這意味着確定的答案,因爲它是在我的其他方法。但是ActiveOrders.Dictionary的 結果是空的。

下面是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") 
     }; 
    } 
} 

的類型是正確的,是我的其他類,它們看起來都一樣。

我想一些想法,使其工作。有什麼建議?

+1

即時通訊做的粉絲:字典<串,對象> OBJ =新詞典<字符串對象>();然後返回新的JavaScriptSerializer()。Serialize(obj); – Fallenreaper

+0

請檢查你傳遞給ActiveOrders.ReadFromJObject的JObject。我感覺你傳遞的是頂級JObject而不是與「return」鍵相關的JObject。 (雖然,根據您的示例JSON,int.Parse然後會解除例外) – elgonzo

回答

3

下面的代碼工作.....

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

完美!謝謝! – Th3B0Y