[英]Can't deserialize this JSON into C# object
我有此JSON,並想將其反序列化為C#中的對象。 請注意,數據字段看起來像字典。
{
"responseID": "LTg5MjUyNDgxMDgyNzU3NjgyNDMtMjAxNi0wNS0xOFQxOTo1ODoxOS45ODFaLTk4MTAwMDAwMA==",
"timestamp": "2016-05-18T19:58:19.981Z",
"type": "v0.1-reject-reason-codes",
"context": {
"tenant": "hpho"
},
"data": {
"LOST_TO_COMPETITOR": "Lost to Competitor",
"OTHER": "Other (see notes)",
"DISCONTINUED": "Product Discontinued",
"SERVICE_ISSUES": "Service Issues",
"SEASONAL": "Seasonal Fluctuations"
}
}
這是類的定義
public static class JSONConstants
{
public const string responseID = "responseID";
public const string timestamp = "timestamp";
public const string type = "type";
public const string context = "context";
public const string data = "data";
public const string tenant = "tenant";
}
[DataContract]
public class RejectReasonCodesResponse
{
[DataMember(Name = JSONConstants.responseID)]
public string ResponseID { get; set; }
[DataMember(Name = JSONConstants.timestamp)]
public string Timestamp { get; set; }
[DataMember(Name = JSONConstants.type)]
public string Type { get; set; }
[DataMember(Name = JSONConstants.context)]
public SummaryContext Context { get; set; }
[DataMember(Name = JSONConstants.data)]
public Dictionary<string, string> Data { get; set; }
}
[DataContract]
public class SummaryContext
{
[DataMember(Name = JSONConstants.tenant)]
public string Tenant { get; set; }
}
這就是我反序列化的方式
string requestURL = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
request.Headers["Ocp-Apim-Subscription-Key"] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK
&& response.StatusCode != HttpStatusCode.NonAuthoritativeInformation)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(RejectReasonCodesResponse));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
但是,objResponse中的“數據”字段為空。 我做錯了什么?
您可以驗證您的類定義嗎? 我認為應該看起來像這樣。
public class SummaryContext
{
public string tenant { get; set; }
}
public class Data
{
public string LOST_TO_COMPETITOR { get; set; }
public string OTHER { get; set; }
public string DISCONTINUED { get; set; }
public string SERVICE_ISSUES { get; set; }
public string SEASONAL { get; set; }
}
public class RejectReasonCodesResponse
{
public string responseID { get; set; }
public string timestamp { get; set; }
public string type { get; set; }
public Context context { get; set; }
public Data data { get; set; }
}
而是嘗試像這樣使用javascriptserializer
javascriptserializer js = new javascriptserializer();
var response = js.Deserialize<RejectReasonCodesResponse>(jsonstring);
首先,使用json.lint之類的站點來填充JSON。 當綠色(如果有)進入Visual Studio並粘貼特殊對象時,可以將json作為類粘貼。 網站Json2csharp也很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.