我有这个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中的数据字段为空。我做错了什么?
答案 0 :(得分:0)
您可以验证您的班级定义吗?我认为它应该是这样的。
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; }
}
答案 1 :(得分:0)
而是尝试使用javascriptserializer
之类的
javascriptserializer js = new javascriptserializer();
var response = js.Deserialize<RejectReasonCodesResponse>(jsonstring);
答案 2 :(得分:0)
首先使用像json.lint这样的网站来抓取JSON。当它的绿色进入visual studio,如果你有它并粘贴特殊,你可以粘贴json作为类。网站Json2csharp也很有用。