这是我第一次使用DataContractSerializer
如果这个问题是基本的,请原谅我,但我似乎无法找到解决方案。
我已经设置了课程AuthTokenContract
[DataContract]
public class AuthTokenContract
{
[DataMember(Name="token")]
public string Token { get; set; }
}
我的方法是将JSON
响应绑定到我的模型
public Guid GetAuthToken()
{
var queryString = new Uri(String.Format("token?apiKey={0}", _apiKey), UriKind.Relative);
var requestUrl = new Uri(_baseUrl, queryString);
var contract = GetResponse<AuthTokenContract>(requestUrl);
return Guid.NewGuid(); // Ignore
}
private TContractType GetResponse<TContractType>(Uri requestUrl) where TContractType : class
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(TContractType));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
return objResponse as TContractType;
}
}
这是我从网址获得的回复:
{
"result":
{
"token":"8D53ED8E-DE75-423B-AC76-DADEF7139D98"
},
"warnings":[]
}
但是,contract.Token
始终是null
。我知道它正在返回上面的JSON
,但我无法正确翻译。有什么帮助吗?
答案 0 :(得分:4)
将合同更改为
[DataContract]
public class AuthTokenContract
{
[DataMember(Name = "result")]
public Result result { get; set; }
[DataMember(Name = "warnings")]
public string[] Warnings { get; set; }
}
[DataContract]
public class Result
{
[DataMember(Name = "token")]
public string Token { get; set; }
}