1

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Cainnech
  • 439
  • 1
  • 5
  • 17

2 Answers2

4

your JSON is formatted incorrectly.
According to this sites validation:

Error: Parse error on line 5:
...     "result": 32    }}, {   "statistics": {
--------------------^
Expecting 'EOF', got ','

This works:

{
    "results": {
        "result": 32
    },
    "statistics": {
        "positive": 47.3,
        "negative": 49.6,
        "breakeven": 3.1
    }
}
Lucky Lindy
  • 133
  • 8
  • That's what I suspected. However the problem is that this is a JSON provided by a third party from whom I don't have any contact details. Is there an easy way to fix this? Right now I'm thinking of re-formatting the reponse. – Cainnech Oct 31 '16 at 17:15
  • Yes. Reformat or let them know that they are sending you junk. [Here](http://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try) is a link on how to verify – Lucky Lindy Oct 31 '16 at 17:21
1

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.

Regards,

Ivan Fontalvo
  • 433
  • 4
  • 21