2

I am not getting JsonConvert.DeserializeObject to work for me. I get the correct value in JSON from the service. Not finding anything online for this, would appreciate a little help here :)

Here is my code:

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void tbPlate_OnServerChange(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(tbPlate.Text))
        {
            var _res = Responses(tbPlate.Text);

            if (_res.Vehicles != null)
            {
                lblTestText.Text = _res.Vehicles.FirstOrDefault(r => r.regNr == tbPlate.Text)?.ToString();
            }
            else
            {
                lblTestText.Text = "No vehicle data"; 
            }
        }
    }

    private static VehicleResults Responses(string regNr)
    {
        var _jSon = "";
        var _url = @"http://apis.is/car";
        var _res = new VehicleResults();

        var _request = (HttpWebRequest)WebRequest.Create($"{_url}?number={regNr}");

        var _response = _request.GetResponse();

        using (var _responseStream = _response.GetResponseStream())
        {
            var _reader = new StreamReader(_responseStream, Encoding.UTF8);
            _jSon = _reader.ReadToEnd();
        }

        _res = JsonConvert.DeserializeObject<VehicleResults>(_jSon);
        return _res;
    }
}

public class VehicleResponse
{
    [JsonProperty("registryNumber")]
    public string regNr { get; set; }
    public string number { get; set; }
    public string factoryNumber { get; set; }
    public string type { get; set; }
    public string subType { get; set; }
    public string color { get; set; }
    public string registeredAt { get; set; }
    public string status { get; set; }
    public string nextCheck { get; set; }
    public string pollution { get; set; }
    public string weight { get; set; }
}

public class VehicleResults
{
    public List<VehicleResponse> Vehicles { get; set; }
}

This is the response JSON from the service:

{"results":[{"type":"MERCEDES BENZ - M (Svartur)","subType":"M","color":"Svartur","registryNumber":"GXS56","number":"GXS56","factoryNumber":"WDC1631131A539035","registeredAt":"23.09.2004","pollution":" g/km","weight":"2200 kg","status":"Í lagi","nextCheck":"01.06.2019"}]}

I am quite new to REST services so I believe that the problem is small....I am just not able to figure it out right now.

3
  • 1
    How could we help you without a sample of your json data that you try to deserialize? Commented Apr 28, 2019 at 21:32
  • {"results":[{"type":"MERCEDES BENZ - M (Svartur)","subType":"M","color":"Svartur","registryNumber":"GXS56","number":"GXS56","factoryNumber":"WDC1631131A539035","registeredAt":"23.09.2004","pollution":" g/km","weight":"2200 kg","status":"Í lagi","nextCheck":"01.06.2019"}]} Commented Apr 28, 2019 at 21:40
  • This is the response JSON from the service Commented Apr 28, 2019 at 21:40

2 Answers 2

5

Your json has a root object that contains the list of your vehicles.
You need to name the variable that holds your list with the name returned in the json. results

public class VehicleResults
{
    // This should be named results
    public List<VehicleResponse> results {get;set;}
}

Now you can deserialize with

VehicleResults data = JsonConvert.DeserializeObject<VehicleResults>(json);
foreach(var vei in data.results)
   Console.WriteLine(vei.type);
Sign up to request clarification or add additional context in comments.

3 Comments

As an alternative to renaming, could attribute the Vehicles property with [JsonProperty("results")]
@Zenilogix Yes exactly
This was the solution.. the naming of Vehicles. public class VehicleResults { [JsonProperty("results")] public List<VehicleResponse> Vehicles { get; set; } }
1

You need to [JsonProperty] on every property in VehicleResponse

Please add _reader.Close() at the end of the using

2 Comments

[JsonProperty] is not needed for property names as they are, but typical convention for property names is that they start with upper-case e.g. "FactoryNumber", not "factoryNumber". If this convention were followed, then [JsonProperty] would be needed e.g. [JsonProperty("factoryNumber")] so that the deserializer will make the correct matches.
I knew this, I was just testing testing if this worked correctly. As you can see, I have named the properties according to the JSON names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.