【发布时间】:2014-09-03 16:22:27
【问题描述】:
我在序列化和反序列化 json 时遇到问题。我一直在寻找答案,虽然我在其他地方看到过同样的问题,但没有一个答案对我有帮助。我在使用 newtonsoft 或 javascriptserializer 时遇到了同样的问题。
我在 rest 服务中的 web 方法
[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 并使用根对象。似乎没有任何效果。我总是得到同样的错误。我相信这里的错误很简单,但我现在看不到。
【问题讨论】:
-
我注意到在您的测试工具 Customer 类中,您只有实例级别的成员,而不是公共属性,就像在您的方法中的 Customer 类中一样。你能改变你的测试工具类来使用公共属性
get;set;吗?看看会发生什么? -
我确实尝试过,但遇到了同样的问题。还是谢谢
标签: c# json vb.net rest json.net