使用json,net将对象序列化为字典

时间:2013-07-09 10:13:02

标签: c# json.net

json.net可以将类对象序列化为一个简单的字典吗?

public class CommitData
{
    public AddressDTO Property { get; set; }

    public DateTime? Appointment { get; set; }

    public DateTime? Closed { get; set; }

    public DateTime? Created { get; set; }

    public string LenderRef { get; set; }

    public string YearBuilt { get; set; }

    public IDictionary<string, object> Custom { get; set; }
 }

public class AddressDTO
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Address3 { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string Postcode { get; set; }
}

序列化时我想获得:

{
"Property.Address1": "",
"Property.Address2": "uyg",
"LenderRef": "yguyg",
"Closed": date_here }

同样将上面的json字符串反序列化为CommitData对象?

1 个答案:

答案 0 :(得分:0)

是的,但这有点工作。通过实现自己的JsonConverter,您可以完全控制对象的序列化和反序列化方式。通过这种方式,您可以通过简单的字符串操作来展平它并使其松散。一个适当的通用解决方案可以完成,但需要更多的工作,因为你需要考虑每个属性的多个级别的递归,但如果你只关心这个案例,那么使用Custom JsonConverter

以下是Json.net内部使用的转换器示例:

KeyValuePairConverter.cs

希望它有所帮助。

相关问题