0

I would parse JSON string received to my ReturnClass (collection of ReturnClass).

My JSON string :

[
    { "EmpId": 1, "Name": "Simone", "City": "Italy" },
    { "EmpId": 2, "Name": "Luca", "City": "Francia" },
    { "EmpId": 1, "Name": "Matteo", "City": "Inghilterra"},
    { "EmpId": 2, "Name": "Marco", "City": "Spagna" }
]

My ReturnClass :

public class ReturnClass   
{
    public int EmpId { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}

This is my code tath doesn't works.. Error of Parsing

HttpResponseMessage response = client.GetAsync(URL).Result;  // Blocking call! 
if (response.IsSuccessStatusCode)
{
    string output = JsonConvert.SerializeObject(response.Content.ReadAsStringAsync().Result);

    JsonConvert.DeserializeObject<ReturnClass>(output);             
}
0

1 Answer 1

2

With this code:

string output = JsonConvert.SerializeObject(response.Content.ReadAsStringAsync().Result);
JsonConvert.DeserializeObject<ReturnClass>(output);

You are:

  • Reading the HTTP response as a string
  • Serializing that string to a JSON string
  • Deserializing that JSON string into one ReturnClass

Apart from the first step, which is merely unnecessary, that is all wrong. There is no need to read the content as a string yourself, you definitely don't want to serialize a JSON string to JSON again, and you're not looking for one ReturnClass, but a collection thereof.

You can simplify the code to this:

var dataFromJson = await client.ReadAsAsync<List<ReturnClass>>();

As an added bonus you won't have to do the deserialization yourself, the HttpClient can do that just fine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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