我在序列化和反序列化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测试工具,调用rest服务并反序列化返回的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设置为包装,以及设置一个根对象。似乎什么都不起作用。我总是得到相同的错误。我相信这里的错误真的很简单,但我现在看不到它。
发布于 2014-09-04 00:44:31
如果您想返回一个通用的json响应,您需要更改您的服务操作契约,以返回消息而不是字符串。
然后,您的服务操作实现应该如下所示:
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);
}https://stackoverflow.com/questions/25649221
复制相似问题