简体   繁体   English

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

[英]Serializing object to dictionary with json,net

Can json.net serialize class objects into a simple dictionary? 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; }
}

When serializing I want to get: 序列化时,我想得到:

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

And similarly deserialize a json string like above into the CommitData object? 并类似地将上述json字符串反序列化为CommitData对象?

Yes, but it is a bit of work. 是的,但这有点工作。 You have full control of how your object is serialized and deserialized by implementing your own JsonConverter . 通过实现自己的JsonConverter您可以完全控制对象的序列化和反序列化JsonConverter With that, you can flatten it and unflatten it by doing simple string manipulation. 这样,您可以通过简单的字符串操作来对其进行展平和取消展平。 A proper generic solution could be acomplished but would take a lot more work as you would need to consider multiple levels of recursion on each property but if you only care about this case in particular then use Custom JsonConverter 适当的通用解决方案可以完成,但是会花费更多的工作,因为您需要考虑每个属性的多个递归级别,但是如果您只关心这种情况,则可以使用Custom JsonConverter

Here is an example of a converter Json.net uses internally: 这是Json.net在内部使用的转换器的示例:

KeyValuePairConverter.cs KeyValuePairConverter.cs

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM