我们正在尝试使用WCF服务,该服务以JSON格式返回员工详细信息。 像:
{"d":[{"__type":"Employee:#","BigThumbNailURI":null,"ID":1,"Name":"E1"},{"__type":"Employee:#","BigThumbNailURI":null,"ID":2,"Name":"E1"}]}
当我试图反序列化时,从VB.net代码背后说明了
反序列化代码段:
Dim serializer = New DataContractJsonSerializer(GetType(List(Of Employee)))
Dim memoryStream = New MemoryStream()
Dim s = msg.Content.ReadAsString()
serializer.WriteObject(memoryStream, s)
memoryStream.Position = 0
' Code for Deserilization
Dim obj As List(Of Employee) = serializer.ReadObject(memoryStream)
memoryStream.Close()
'Employee Class
<DataContract()> _
Public Class Employee
Private _Name As String
<DataMember()> _
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Private _id As Integer
<DataMember()> _
Public Property ID() As Integer
Get
Return _id
End Get
Set(ByVal value As Integer)
_id = value
End Set
End Property
End Class
有没有人遇到过这个问题?
答案 0 :(得分:2)
找到解决方案。要解决此问题,请不要再使用该MemoryStream。 将JSON对象直接传递给反序列化器,如下所示:
Dim serializer = New DataContractJsonSerializer(GetType(List(Of Employee)))
' Code for Deserilization
Dim obj As List(Of Employee) = serializer.ReadObject(msg.Content.ReadAsString())
memoryStream.Close()
答案 1 :(得分:0)
以下是两种用于序列化和反序列化的通用方法。
/// <summary>
/// Serializes the specified object into json notation.
/// </summary>
/// <typeparam name="T">Type of the object to be serialized.</typeparam>
/// <param name="obj">The object to be serialized.</param>
/// <returns>The serialized object as a json string.</returns>
public static string Serialize<T>(T obj)
{
Utils.ArgumentValidation.EnsureNotNull(obj, "obj");
string retVal;
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
serializer.WriteObject(ms, obj);
retVal = Encoding.UTF8.GetString(ms.ToArray());
}
return retVal;
}
/// <summary>
/// Deserializes the specified json string into object of type T.
/// </summary>
/// <typeparam name="T">Type of the object to be returned.</typeparam>
/// <param name="json">The json string of the object.</param>
/// <returns>The deserialized object from the json string.</returns>
public static T Deserialize<T>(string json)
{
Utils.ArgumentValidation.EnsureNotNull(json, "json");
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
}
return obj;
}
您需要这些名称空间
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;