JSON Restful服务。无法从System.String转换或转换为System.Collections.Generic.List

时间:2014-09-03 16:22:28

标签: c# json vb.net rest json.net

我在序列化和反序列化json时遇到问题。我已经找到了答案,虽然我在其他地方看到了同样的问题,但没有答案帮助了我。我在使用newtonsoft或javascriptserializer时遇到了同样的问题。

我在休息服务中的网络方法

[OperationContract(Name="Customers")]
[WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "json/Customer/Read/{CustomerID}/{CustomerCode}/{ParentCustomerID}/{CustomerName}")]
String JSONReadCustomers(String CustomerID, String CustomerCode, String ParentCustomerID, String CustomerName);

班级

public class Customer
{
    public Int32 CustomerID { get; set; }
    public String CustomerCode { get; set; }
    public String CustomerName { get; set; }
    public Customer(DataRow DR)
    {
        CustomerID = Convert.ToInt32(DR["CustomerID"]);
        CustomerCode = (DR["CustomerCode"] != null) ? DR["CustomerCode"].ToString() : "";
        CustomerName = (DR["CustomerName"] != null) ? DR["CustomerName"].ToString() : "";
    }
}

实际执行序列化的位

private String GetJSON(DataTable DT)
{
    try
    {
        List<Customer> customers = new List<Customer>();
        foreach (DataRow DR in DT.Rows)
        {
            customers.Add(new Customer(DR));
        }

        return JsonConvert.SerializeObject(customers);
    }
    catch
    {
        throw;
    }
}

到目前为止一切似乎都没问题。 该服务编译并运行正常。当我在浏览器中测试它时,我得到以下结果

"[{\"CustomerID\":1,\"CustomerCode\":\"AMT-1\",\"CustomerName\":\".AMTDisp\"},{\"CustomerID\":2,\"CustomerCode\":\"COM-2\",\"CustomerName\":\".ComexDisp,_\"}]"

我有一个VB测试工具我正在使用调用其余服务并反序列化返回的json

班级

Public Class Customer
    Public CustomerID As Int32
    Public CustomerCode As String
    Public CustomerName As String
End Class

方法

Private Function DeserializeJSON() As List(Of Customer)

    Dim request As WebRequest = WebRequest.Create(GetCustomerURL())
    request.Credentials = CredentialCache.DefaultCredentials
    Dim response As WebResponse = request.GetResponse()
    Dim dataStream As Stream = response.GetResponseStream()

    Dim reader As New StreamReader(dataStream)
    Dim responseJSON As String = reader.ReadToEnd()

    Dim customers As List(Of Customer) = JsonConvert.DeserializeObject(Of List(Of Customer))(responseJSON)
    Return customers

End Function

错误

{"Could not cast or convert from System.String to System.Collections.Generic.List`1[RESTTestHarness.Customer]."}

我使用了各种不同的方法,例如将bodystyle设置为Wrapped并拥有根对象。似乎没什么用。我总是得到同样的错误。我相信错误在这里非常简单,但我现在看不到它。

1 个答案:

答案 0 :(得分:0)

如果要返回通用的json响应,则需要更改服务操作合同以返回Message而不是字符串,

您的服务操作实现应该类似于:

public System.ServiceModel.Channels.Message CreateJsonResponse()
{
  List<Customer> response = GetCustomers(); 

  string msg = JsonConvert.SerializeObject(response);

  return WebOperationContext.Current.CreateTextResponse(msg, "application/json; charset=utf-8", Encoding.UTF8);
}