[英]Deserialize to object with custom object property
I have a class like so: 我有一个像这样的课程:
public class CareTaker
{
public int Id {get; set;}
public string name {get; set;}
public DateTime? DateTrained {get; set;}
public Certification Certification {get; set;}
public List<Certification> ExpiredCertifications {get; set;}
}
public class Certification
{
public int Id {get; set;}
}
and my JSON is like so: 而我的JSON就像这样:
{
"id": 1,
"name": "Dogtor",
"dateTrained": "01 Feb 2017",
"certification": 2,
"expiredCertifications": [1,5]
}
I know usually the JSON for Certification
should really be like "certification": { "id": 2}
, but, I don't have access to change the JSON so I have to figure out how to convert what I recieve ( "certification": 2
) to my object... Is there a way I can do this with either JavascriptSerializer or NewtonSoft please? 我知道通常来说,用于Certification
的JSON确实应该像"certification": { "id": 2}
,但是,我无权更改JSON,因此我必须弄清楚如何转换我收到的内容( "certification": 2
)到我的对象...请问有什么方法可以用JavascriptSerializer或NewtonSoft来做到这一点?
You could do something like this: 您可以执行以下操作:
public class CareTaker
{
...
[NotMapped]
[JsonProperty(PropertyName = "certification"]
public int? CertificationId
{
get
{
return Certification?.Id;
}
set
{
Certification = new Certification { Id = value; }
}
}
[JsonIgnore]
public Certification Certification {get; set;}
...
}
To generate properly the classes, I would suggest copying the JSON and open the file where you want to store the classes and in visual studio go to EDIT->Paste Special->Paste JSON As Classes 为了正确生成类,我建议复制JSON并打开要在其中存储类的文件,然后在Visual Studio中转到EDIT-> Paste Special-> Paste JSON As Classes
then you would do something like this: 那么您将执行以下操作:
JavaScriptSerializer ser = new JavaScriptSerializer();
var jsonToClasses = ser.Deserialize<RootObject>(json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.