[英]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.