2013-04-24 53 views
2

如何將json接受單個值作爲數組?json接受單個值作爲數組

此JSON拋出異常:

{ 「代碼」: 「1」, 「消息」: 「OK」, 「迴應」:{ 「合作伙伴」: { 「ID 「:」33「, 」name「:」「, 」clienttypeid「:」29「, 」logo「:」「, 」description「:」「, 」website「:」www.site.com 「 } } }

此JSON解析正確的:

{ 「代碼」: 「1」, 「消息」: 「OK」, 「響應」:{ 「夥伴」:[ { 「ID」: 「33」, 「名」: 「」, 「clienttypeid」: 「29」, 「標誌」: 「」, 「說明」: 「」, 「網站」:「WWW。 site.com「 }, { 「ID」: 「34」, 「名」: 「」, 「clienttypeid」: 「29」, 「標誌」: 「」, 「說明」: 「」, 「網站」:「WWW。 site.com」 } ] }}

型號:

public class Partner 
{ 
    public string id { get; set; } 
    public string name { get; set; } 
    public string clienttypeid { get; set; } 
    public string logo { get; set; } 
    public string description { get; set; } 
    public string website { get; set; } 
} 

public class Response 
{ 
    public List<Partner> partners { get; set; } 
} 

public class RootObject 
{ 
    public string code { get; set; } 
    public string message { get; set; } 
    public Response response { get; set; } 
} 

回答

2

如果你試圖反序列化到List,使用數組表示法,即使有一個元素

{ 
    "code":"1", 
    "message":"OK", 
    "response":{ 
     "partners":[ 
      { 
       "id":"33", 
       "name":"", 
       "clienttypeid":"29", 
       "logo":"", 
       "description":"", 
       "website":"www.site.com" 
      } 
     ] 
    } 
} 
+0

服務器不返回數組符號[...]如果值是單 – 2013-04-24 13:04:21

1

我用Json.netpartners轉換成數組,如果它是一個單一的對象

string Normalize(string json) 
{ 
    var jobj = JObject.Parse(json); 
    if (!(jobj["response"]["partners"] is JArray)) 
    { 
     jobj["response"]["partners"] = new JArray(jobj["response"]["partners"]); 
    } 
    return jobj.ToString(); 
}