Cainnech Cainnech - 1 year ago 84
C# Question

Invalid format of JSON-reponse?

I'm having issues trying to deserialize the JSON received from an external source. I'm not sure but I think it might be the JSON itself which is wrong, or else I'm doing it all wrong. Could someone shed a light on this?

This is the JSON I'm receiving:

{"results": {"result": 32}},{"statistics": {"positive": 47.3,"negative": 49.6,"breakeven": 3.1}}

These are my classes:

public class dataClass
public resultsClass results { get; set; }
public statisticsClass statistics { get; set; }

public class resultsClass
public int result { get; set; }

public class statisticsClass
public Double? positive { get; set; }
public Double? negative { get; set; }
public Double? breakeven { get; set; }

And this is how I deserialize:

dataClass output = JsonConvert.DeserializeObject<dataClass>(response);

When I try to deserialize this, I'm getting the error:

Additional text encountered after finished reading JSON content

And I've pinned it down to the comma in between the results and the statistics. I think the closing bracket of results and the opening bracket of statistics should not be there.

Or am I deserializing wrong?

Answer Source

If you parse the json into a text editor you can see that in that response you have double root element. the result , and the statistics are separated.

You have to choice :

  1. Separate the string json : You have to split the two root element and aply the JsonConvert.DeserializeObject<dataClass>(response); for each root element
  2. Modify the json response stucture (Recommended): the json response is wrong !! , if you are the owner of the response you can modify the response to this : { "results": { "result": 32 }, "statistics": { "positive": 47.3, "negative": 49.6, "breakeven": 3.1 } } and should be works with your code.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download