【问题标题】:Serializing object to dictionary with json,net使用 json,net 将对象序列化为字典
【发布时间】:2013-07-09 10:13:02
【问题描述】:

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 对象中?

【问题讨论】:

  • 你看到这个了吗:stackoverflow.com/questions/15333820/…?一般来说,它似乎不能用 JSON.NET 来完成。无论如何,JSON.NET 会将您的地址序列化为它自己的对象,因此在反序列化时,您将获得一个带有AddressDTO 属性的CommitData 对象,您可以像往常一样使用. 访问该属性。

标签: c# json.net


【解决方案1】:

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

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

KeyValuePairConverter.cs

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多