解析值时遇到意外字符:{

时间:2019-05-22 15:11:34

标签: serialization json.net

我正在尝试使用Newtonsoft.JSON.JsonConvert.DeserializeObject解析一些JSON-实际上,JSON也是由Newtonsoft从我要反序列化为同一类的类中生成的,并且绝对有效。

但这给了我一个例外:Newtonsoft.Json.JsonReaderException : Unexpected character encountered while parsing value: {.

我已经做了一个非常简单的例子来说明问题。

这是JSON:

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

这是一个简化的模型,仍然显示了问题:

public class Person
{
    public Address Address;
}

public class Address
{
    public Country Country;

    public Address(string country)
    {
    }
}

public class Country
{
    public string Name;
}

以下是失败的代码:

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

我已经检查过了,这与C# - Unexpected character encountered while parsing value: {. Path '[0].StatisticsUnexpected character encountered while parsing API response不同。现在,我已经解决了这个问题(请参阅下面的答案),这与这两个问题都不相同。

1 个答案:

答案 0 :(得分:0)

这个简短的答案是,确保与报告问题的路径的直接父级相对应的类(上述异常消息中的路径为'address.country';其直接父级为'address' )具有公共的无参数构造函数。

因此,在上面,您必须向Address类添加一个公共的无参数构造函数。


这是示例中的Address类,其中有一些注释解释了发生的情况:

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)
    {
    }
}