0

I am trying to parse some JSON with Newtonsoft.JSON.JsonConvert.DeserializeObject - in fact the JSON was also generated by Newtonsoft from the same classes I am trying to deserialize into, and is definitely valid.

But it is giving me the exception: Newtonsoft.Json.JsonReaderException : Unexpected character encountered while parsing value: {.

I've made a very simplified example to show the problem.

Here is the JSON:

{
  "address": {
    "country": {
      "name": "UK"
    }
  }
}

Here is a simplified model which still shows the problem:

public class Person
{
    public Address Address;
}

public class Address
{
    public Country Country;

    public Address(string country)
    {
    }
}

public class Country
{
    public string Name;
}

Here is the code which fails:

// Fails with Newtonsoft.Json.JsonReaderException : "Unexpected character encountered
// while parsing value: {. Path 'address.country', line 3, position 16."
Person item = JsonConvert.DeserializeObject<Person>(json);

I have checked, and this is not the same problem as C# - Unexpected character encountered while parsing value: {. Path '[0].Statistics or Unexpected character encountered while parsing API response . I have now worked out the issue (see my answer below), and it is NOT the same problem or solution as either of those two.

MikeBeaton
  • 3,314
  • 4
  • 36
  • 45

1 Answers1

0

This short answer is, make sure that the class corresponding to the immediate parent of the path where the problem is reported (the path is 'address.country' in the above exception message; its immediate parent is 'address') has a public parameterless constructor.

So, in the above you must add a public parameterless constructor to your Address class.


Here is the Address class from the example with some comments explaining what is going on:

public class Address
{
    public Country Country;

    // With this present the JSON parses just fine!
    public Address() { }

    // Because both of the following were true:
    //  1) the name of a parameter here matches the name of a field to be populated and
    //  2) there was no public parameterless constructor
    // this was constraining what could appear in the JSON to populate "address"!
    public Address(string country)
    {
    }
}
MikeBeaton
  • 3,314
  • 4
  • 36
  • 45