无法将Json数组反序列化为类型字符串

时间:2014-02-28 11:28:29

标签: json winforms c#-4.0

跟随我的代码片段,反序列化Json字符串。

  response = "{\"success\":\"yes\",\"error\":\"\",\"message\":\"\",\"arguments\":[{\"id\":\"72820\",\"rowNo\":\"1\",\"userId\":\"40\",\"entityId\":\"3486\",\"value\":\"search Panel\",\"typeCategory\":\"3\"}]}";

        erpAPIResponse basicResponse = JsonConvert.DeserializeObject<erpAPIResponse>(response);

结果是JSON字符串,它被反序列化为erpAPIResponse。

我的erpAPIResponse如下:

public string success { get; set; } // getting and setting the success
    public string error { get; set; } // getting and setting the error
    public string message { get; set; } // getting and setting the message
    public string arguments { get; set; } // getting and setting the arguments
   // public string result { get; set; }

我已经通过JSON Lint验证了json,并且它说它是有效的JSON字符串。那么为什么我会得到这个错误呢?

1 个答案:

答案 0 :(得分:2)

因为你的json结构如下所示:

{
    "success": "yes",
    "error": "",
    "message": "",
    "arguments": [
        {
            "id": "72820",
            "rowNo": "1",
            "userId": "40",
            "entityId": "3486",
            "value": "search Panel",
            "typeCategory": "3"
        }
    ]
}

在这里,您无法反序列化字符串中的arguments数组。因此,您需要使用json2csharp实用程序

重新定义erpAPIResponse类,如下所示
public class erpAPIResponse
{
    public string success { get; set; }
    public string error { get; set; }
    public string message { get; set; }
    public List<Argument> arguments { get; set; }
}

public class Argument
{
    public string id { get; set; }
    public string rowNo { get; set; }
    public string userId { get; set; }
    public string entityId { get; set; }
    public string value { get; set; }
    public string typeCategory { get; set; }
}

现在,使用原始语句反序列化应该没有问题:

response = "{\"success\":\"yes\",\"error\":\"\",\"message\":\"\",\"arguments\":[{\"id\":\"72820\",\"rowNo\":\"1\",\"userId\":\"40\",\"entityId\":\"3486\",\"value\":\"search Panel\",\"typeCategory\":\"3\"}]}";

erpAPIResponse basicResponse = JsonConvert.DeserializeObject<erpAPIResponse>(response);