使用自定义对象属性反序列化为对象

时间:2016-02-06 09:38:40

标签: c# json.net deserialization

我有一个类似的课程:

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;}
}

我的JSON是这样的:

{
    "id": 1,
    "name": "Dogtor",
    "dateTrained": "01 Feb 2017",
    "certification": 2,
    "expiredCertifications": [1,5]
}

我知道Certification的JSON通常应该像"certification": { "id": 2}一样,但是,我无法更改JSON,所以我必须弄清楚如何转换我收到的内容("certification": 2)我的对象......我有可能通过JavascriptSerializerNewtonSoft来做到这一点吗?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

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;}
    ...
}

答案 1 :(得分:0)

为了正确生成类,我建议复制JSON并打开要存储类的文件,然后在visual studio中转到EDIT-&gt; Paste Special-&gt;将JSON粘贴为类

那么你会做这样的事情:

JavaScriptSerializer ser = new JavaScriptSerializer();
var jsonToClasses = ser.Deserialize<RootObject>(json);