Question

This is the first time I've used the DataContractSerializer so forgive me if this question is basic, but I can't seem to find a solution.

I've set up the class AuthTokenContract

[DataContract]
public class AuthTokenContract
{
    [DataMember(Name="token")]
    public string Token { get; set; }
}

And my method to bind the JSON response to my model

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;
    }
}

This is the response I am getting from the URL:

{
    "result":
        {
            "token":"8D53ED8E-DE75-423B-AC76-DADEF7139D98"
        },
    "warnings":[]
}

However, contract.Token is always null. I know it is returning the JSON above, but I can't get it to translate correctly. Any help?

Was it helpful?

Solution

Change your contract to

[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; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top