json接受单个值作为数组

时间:2013-04-24 12:56:21

标签: c# .net json

如何将json接受单个值作为数组?

这个json抛出异常:

  

{        “code”:“1”,        “消息”:“好的”,        “回应”:{           “伙伴”:               {                   “id”:“33”,                   “名称”: ””,                   “clienttypeid”:“29”,                   “商标”: ””,                   “description”:“”,                   “网站”:“www.site.com”               }           }       }

这个json解析正确:

  

{       “code”:“1”,       “消息”:“好的”,       “回应”:{           “伙伴”: [               {                   “id”:“33”,                   “名称”: ””,                   “clienttypeid”:“29”,                   “商标”: ””,                   “description”:“”,                   “网站”:“www.site.com”               },               {                   “id”:“34”,                   “名称”: ””,                   “clienttypeid”:“29”,                   “商标”: ””,                   “description”:“”,                   “网站”:“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 个答案:

答案 0 :(得分:2)

如果您尝试反序列化为List,请使用数组表示法,即使只有一个元素

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

答案 1 :(得分:2)

我使用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();
}