我正在尝试反序列化来自 google api 的 json 响应,所以我想我会定义几个类来帮助它:
[DataContract]
public class DetectionResult:ResponseData
{
[DataMember(Name="language")]
public string Language
{ get; set; }
[DataMember(Name="isReliable")]
public bool IsReliable
{ get; set; }
[DataMember(Name="confidence")]
public double Confidence
{get;set;}
}
[DataContract]
public abstract class ResponseData
{
[DataMember(Name = "error")]
public TranslationError Error
{ get; set; }
}
[DataContract]
public class TranslationError
{
[DataMember(Name="code")]
public int Code
{ get; set; }
[DataMember(Name="message" )]
public int Message
{ get; set; }
}
[DataContract]
[KnownType(typeof(DetectionResult))]
public class RequestResult
{
[DataMember(Name="responseStatus")]
public int ResponseStatus
{ get; set; }
[DataMember(Name="responseDetails")]
public string ResponseDetails
{ get; set; }
[DataMember(Name = "responseData")]
public ResponseData Response
{ get; set; }
}
我提出请求后得到的响应是:
{"responseData": {"language":"en","isReliable":false,"confidence":0.114892714}, "responseDetails": null, "responseStatus": 200}
并使用此代码对其进行反序列化:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RequestResult));
RequestResult result = (RequestResult)serializer.ReadObject(stream);
stream.Close();
}
但是我收到一个异常说明“无法创建抽象类”。它不应该知道 DetectionResult 类并正确反序列化它吗?