c# - 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 行,位置...
我发现了这个,但我无法弄清楚。
如何修复这些问题。任何帮助表示赞赏。
解决方案
尝试
[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 属性也必须是一个字符串。
推荐阅读
- javascript - MongoDB 连接到 Robo 3T 但数据不显示
- c# - 有人可以帮我修复这个跳转脚本吗?
- typescript - 如何在 TypeScript 中为静态方法转换添加函数类型?
- google-apps-script - 如何将 Gumroad API 与 Google Apps 脚本集成
- angular - 使用模型和表单组指令时无法找到带有路径的控件
- docker - docker-compose 中的 InfluxDB 无法允许连接
- discord.py - 在 python 中制作一个不和谐的机器人
- r - 根据月份或季度拆分时间序列数据以比较均值和方差值
- node.js - 使用 JWT 对 Angular Universal 进行身份验证
- python - 如何在代码中使用将与 exe 一起打包的附加文件?