2014-03-12 35 views
1

我正在使用Json.Net DeserializeObject Json數據。JsonNET解碼列表

這就是我的Json

string datosContratos = {"Total":1,"Contrato":[{"Numero":1818,"CUPS":"ES003L0P","Direccion":"C. O ","TextoCiudad":"MADRID","Tarifa":"2"}]} 

我的類別是:

public class Contrato 
{ 
    public int Numero; 
    public String Cups; 
    public String Direccion; 
    public String TextoCiudad; 
    public String Tarifa; 
} 

public class Contratos 
{ 
    public int Total { get; set; } 
    public List<Contrato> ListaContratos { get; set; } 
} 

當我deseralize:

Contratos contratos = JsonConvert.DeserializeObject<Contratos>(datosContratos); 

而結果是,contratos.Total是正確的(在此情況1),但ListaContratos爲空,儘管它應該填充數據。我沒有看到問題!

回答

2

你的類必須有相同的變量名作爲你的JSON,所以它應該是這樣的:

public class Contratos 
{ 
    public int Total { get; set; } 
    public List<Contrato> Contrato { get; set; } 
} 
+0

謝謝!有用。我假設解碼是基於類型的,而不是以變量名稱。對我來說錯誤 – Tekno

2

在你JSON串有屬性稱爲Contrato,而在你的類Contrato名單宣佈爲ListaContratos

變化JSON字符串

string datosContratos = {"Total":1, 
         "ListaContratos ":[{"Numero":1818, 
              "CUPS":"ES003L0P", 
              "Direccion":"C. O ", 
              "TextoCiudad":"MADRID", 
              "Tarifa":"2"}]} 

改變類定義

public class Contratos 
{ 
    public int Total { get; set; } 
    public List<Contrato> Contrato { get; set; } 
}