首页 > 解决方案 > C# Entity Framework Json 反序列化字符串数组问题

问题描述

我有一个 Json 文件,可用于反序列化为实体框架。为了简化,我们可以假设 Json 像这样

{
  "stat": "val0",
  "results": [
    {
      "datasets": [
        "val1",
        "val2"
      ],
      "head": "val3"
    },
    {
      "datasets": [
        "val4",
        "val5"
      ],
      "head": "val6"
    }
  ]
} 

我的实体类喜欢

[Serializable]
public class Root
{
    [Key]
    public int Id { get; set; }
    public int stat { get; set; }
    public List<Result> results { get; set; }
}

[Serializable]
public class Result
{
    [Key]
    public int Id { get; set; }
    public List<String> _strings { get; set; }
    public List<string> Strings
    {
        get { return _strings; }
        set { _strings = value; }
    }

    [Required]
    public string datasets
    {
        get { return String.Join(",", _strings); }
        set { _strings = value.Split(',').ToList(); }
    }
    public string head{ get; set; }
    public virtual root { get; set; }

}

我知道 Entity Framework 不支持原始类型,并且我知道来自我的数据集字段的问题原因。我在这里找到了解决字符串数组反序列化问题方法。我努力了

 URL = "http://...";//Restful webservice address
 WebClient client = new WebClient();
 String JSON= client.DownloadString(URL);
 var dsobj = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(json);

但我得到了

System.InvalidOperationException

然后我决定使用 Newtonsoft

URL = "http://...";//Restful webservice address
WebClient client = new WebClient();
String JSON= client.DownloadString(URL);
var dsobj = JsonConvert.DeserializeObject<Root>(json);

然后我得到了这个错误

Newtonsoft.Json.JsonReaderException:'解析值时遇到意外字符:[。路径 'results[0].senses[0].definition',第 1 行,位置...

我发现了这个,但我无法弄清楚。

如何修复这些问题。任何帮助表示赞赏。

标签: c#jsonentity-frameworkentity-framework-6deserialization

解决方案


尝试

[Serializable]
public class Root
{
    [Key]
    public int Id { get; set; }
    public string stat { get; set; } // changed to a string
    public List<Result> results { get; set; }
}

[Serializable]
public class Result
{
    [Key]
    public int Id { get; set; }
    public List<String> _dataSets { get; set; }
    public List<string> dataSets // the JSON array will deserialize into this property
    {
        get { return _dataSets; }
        set { _dataSets = value; }
    }

    [Required]
    public string DatasetsAsString
    {
        get { return String.Join(",", _dataSets); }
        set { _dataSets = value.Split(',').ToList(); }
    }
    public string head{ get; set; }
    public virtual root { get; set; }

}

编辑: stat 属性也必须是一个字符串。


推荐阅读