Search code examples
c#jsonrestserializationjson-deserialization

JSON Deserialization in c# receiving null values in all data members


Below is the valid JSON which my service is returning upon invocation:

[{
   "CCRQ": "2006/1/26 0:00:00",
   "CLXH": "CA6510B1",
   "CarBodyColor": "color"
}]

Below is my code containing datamembers:

[DataContract]
public class Response
{
    [DataMember(Name = "CCRQ")]
    public string CCRQ { get; set; }

    [DataMember(Name = "CLXH")]
    public string CLXH { get; set; }

    [DataMember(Name = "CarBodyColor")]
    public string CarBodyColor { get; set; }
}

However I am making a request to service and receiving null in all data members.

public static Response MakeRequest(string requestUrl)
{
    HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));

        object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
        Response jsonResponse = objResponse as Response;
        return jsonResponse;
    }
}

Why am I getting null in all the attributes?


Solution

  • Your JSON is an array with 1 object content. For what I can see, your deserializer expects an object.

    try as response

    {
       "CCRQ": "2006/1/26 0:00:00",
       "CLXH": "CA6510B1",
       "CarBodyColor": "color"
    }
    

    or cast response to objResponse as List<Response>