解析值后,遇到意外字符:6。路径'[0]

时间:2017-05-10 18:37:33

标签: c# json wpf json.net

我正在使用Newtonsoft库(Json.Net)从文件中解析JSON对象。我在jsonlint.com验证了JSON,它是有效的。

但是当我说:

using (StreamReader sr = new StreamReader(path))
{
    json = await sr.ReadToEndAsync();
}
ContactsCollection = JsonConvert.DeserializeObject<List<Contact>>(json); //error

我收到错误:

  

解析值后,遇到意外字符:6。路径'[0]

所以我在json = await sr.ReadToEndAsync();放了一个断点,显示的JSON值为:

"\0{\0\"\0F\0i\0r\0s\0t\0N\0a\0m\0e\0\"\0:\0\"\0N\0i\0k\0h\0\"\0,\0\"\0L\0a\0s\0t\0N\0a\0m\0e\0\"\0:\0\"\0A\0N\0S\0\"\0,\0\"\0D\0a\0t\0e\0O\0f\0B\0i\0r\0t\0h\0\"\0:\0\"\01\02\0/\07\0/\01\09\08\09\0 \01\02\0:\00\00\0:\00\00\0 \0A\0M\0\"\0,\0\"\0W\0e\0i\0g\0h\0t\0\"\0:\01\06\08\0.\00\0,\0\"\0H\0e\0i\0g\0h\0t\0\"\0:\01\06\08\0.\00\0,\0\"\0P\0h\0o\0n\0e\0\"\0:\0\"\0(\08\00\05\0)\0 \02\05\01\0-\01\00\01\05\0\"\0}\0]\0"

这是我的实际JSON:

[{
  "FirstName":"Nikh",
  "LastName":"ANS",
  "DateOfBirth":"12/7/1989 12:00:00 AM",
  "Weight":168.0,
  "Height":168.0,
  "Phone":"(805) 251-1015"
}]

这是我的联系人课程:

public class Contact : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            NotifyPropertyChanged("FirstName");
        }
    }

    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set
        {
            _lastName = value;
            NotifyPropertyChanged("LastName");
        }
    }

    private string _dateOfBirth;
    public string DateOfBirth
    {
        get { return _dateOfBirth; }
        set
        {
            _dateOfBirth = value;
            NotifyPropertyChanged("DateOfBirth");
        }
    }

    private double _weight;
    public double Weight
    {
        get { return _weight; }
        set
        {
            _weight = value;
            NotifyPropertyChanged("Weight");
        }
    }

    private double _height;
    public double Height
    {
        get { return _height; }
        set
        {
            _height = value;
            NotifyPropertyChanged("Height");
        }
    }

    private string _phone;
    public string Phone
    {
        get { return _phone; }
        set
        {
            _phone = value;
            NotifyPropertyChanged("Phone");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

有谁知道可能出现的问题?

2 个答案:

答案 0 :(得分:3)

这看起来像编码问题。我打赌您的文件以UTF-16编码保存,但您正在将其读作UTF-8。 (UTF-8是StreamReader的默认编码。)这可以解释为什么在读取JSON值的中间有各种\0个字符,以及为什么Json.Net在解析它时遇到问题。初始化StreamReader时尝试指定编码:

    using (StreamReader sr = new StreamReader(path, Encoding.Unicode, true))
    {
        ...
    }

或者,确保使用UTF-8编码保存您的JSON文件。

答案 1 :(得分:0)

检查流路径是否正确设置了其位置。也许在调用path.Position = 0;

之前添加行sr.ReadToEndAsync();