嘿伙计们,我正在尝试反序列化来自 API 的 JSON 响应,然后显示数据。我以字符串的形式获取响应并尝试将其映射到对象。这是来自 twitter 的回复,它回复了多条推文,所以我试图将其映射到推文列表。
我收到以下异常。
System.InvalidOperationException: Type 'Default3+TwitterApiData' is not supported for deserialization of an array. at System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, Boolean throwOnError, IList& convertedList) at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject) at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input) at Default3.Page_Load(Object sender, EventArgs e)
这可能是因为我没有 JSON 中每个键值对的数据成员吗?返回的 JSON 就像 60 KV 对,我不需要所有数据,所以我只有两个成员。
还是我在反序列化为对象数组时做错了什么?下面是我正在进行反序列化的代码。
在此先感谢您的帮助。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resourceUrl);
request.Headers.Add("Authorization", authorizationHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
try
{
WebResponse response = request.GetResponse();
var responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
TwitterApiData twitterApiResponse = new JavaScriptSerializer().Deserialize<TwitterApiData>(responseData);
foreach (var item in twitterApiResponse.data)
{
lblResponse.InnerText = "created_at: " + item.created_at + " text: " + item.text;
}
}
catch (Exception ex)
{
lblResponse.InnerText = ex.ToString();
}
然后我映射到的对象。还看这个我需要 [DataContract] 和 [DataMember] 属性吗?
public class TwitterApiData
{
public List<Tweet> data { get; set; }
}
public class Tweet
{
public string created_at { get; set; }
public string text { get; set; }
}