简体   繁体   中英

Serializing object to dictionary with json,net

Can json.net serialize class objects into a simple dictionary?

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?

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

Here is an example of a converter Json.net uses internally:

KeyValuePairConverter.cs

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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