【发布时间】:2019-06-16 06:06:46
【问题描述】:
我有一个可用于反序列化为实体框架的 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 不支持原始类型,并且我从我的数据集字段中知道问题的原因。我发现这种方法可以解决字符串数组反序列化问题here。我试过了
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 行,位置...
我找到了this,但我想不通。
如何修复这些问题。任何帮助表示赞赏。
【问题讨论】:
-
datasetsJSON 数组应与实体类中的List<string>匹配。试试public List<string> dataSets和public string datasetsAsString。 -
我听不懂@michaelyin 你能告诉我吗?
标签: c# json entity-framework entity-framework-6 deserialization