2015-03-31 49 views
0

我從web服務的結果,該字符串結果是:爲什麼JsonConvert.DeserializeObject不起作用?

{"status":"success","data":{"address":"[email protected]","unconfirmed":[{"tx":"cb2f252078d933f63d9cef52bee8857427d70c1142f41f10567cfad7ef1d2dcb","time_utc":"2015-03-31T19:05:09Z","amount":0.1,"n":0},{"tx":"a34fc5b8b3c29c7046ca8acaedd39280f81597a853f30825856e2f46e498c478","time_utc":"2015-03-31T19:05:01Z","amount":0.1,"n":0}]},"code":200,"message":""} 

我打電話JsonConvert.DeserializeObject:

UTByAddressessResponse數據= Serializer.Deserialize(結果);

public static T Deserialize<T>(string json) 
     { 
      return JsonConvert.DeserializeObject<T>(json); 
     } 




public class UTByAddressessResponse 
    { 
     public string status { get; set; } 
     public UnconfirmedAddressInfo[] data { get; set; } 

     public string code { get; set; } 
     public string message { get; set; } 
    } 


public class UnconfirmedAddressInfo 
    { 
     public string address { get; set; } 
     public List<UT> unconfirmed { get; set; } 
    } 



public class UT 
    { 
     public string tx { get; set; } 
     public DateTime time_utc { get; set; } 
     public float amount { get; set; } 
     public long n { get; set; } 
    } 

但是要得到一個錯誤:

無法反序列化當前JSON對象(例如{ 「名稱」: 「值」}) 成型「Dice.Common.Objects.UnconfirmedAddressInfo [] '因爲 類型需要JSON數組(例如[1,2,3])才能正確地反序列化。

爲什麼?

回答

1

的問題是,

public class UTByAddressessResponse 
    { 
     public string status { get; set; } 
     public UnconfirmedAddressInfo[] data { get; set; } 

     public string code { get; set; } 
     public string message { get; set; } 
    } 

應該

public class UTByAddressessResponse 
    { 
     public string status { get; set; } 
     public UnconfirmedAddressInfo data { get; set; } // not array 

     public string code { get; set; } 
     public string message { get; set; } 
    } 
1

您的JSON粘貼到http://json2csharp.com/這將創建下列類別

public class Unconfirmed 
{ 
    public string tx { get; set; } 
    public string time_utc { get; set; } 
    public double amount { get; set; } 
    public int n { get; set; } 
} 

public class Data 
{ 
    public string address { get; set; } 
    public List<Unconfirmed> unconfirmed { get; set; } 
} 

public class RootObject 
{ 
    public string status { get; set; } 
    public Data data { get; set; } 
    public int code { get; set; } 
    public string message { get; set; } 
} 

現在你可以反序列化作爲

var obj = JsonConvert.DeserializeObject<RootObject>(json_string); 

PS:你可以爲你的類名,但如果要重命名的屬性,您應該使用JsonProperty屬性。