Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to serialize one property of an object of arrays

I have the following model

public class MyModel {
    public string Title;
    public string Description;
    public string Date;
}

I now have an IEnumerable object containing many MyModels

{
    data: [
        {
            Title: xxx,
            Description: yyy,
            Date: 2024-12-03
        },
        {
            Title: xxx,
            Description: yyy,
            Date: 2024-12-04
        },
        {
            Title: xxx,
            Description: yyy,
            Date: 2024-12-05
        },
        {
            Title: xxx,
            Description: yyy,
            Date: 2024-12-06
        }
    ]
}

What I would like to do is to serialize just the dates. How would I go about this? The following obviously doesn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var serialized = JsonConvert.SerializeObject(data.date)

>Solution :

If data is a collection of MyModel instances and you want just a collection of string instances of a single property of that model, you can use .Select() to project the former into the latter. For example:

var serialized = JsonConvert.SerializeObject(data.Select(d => d.Date));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading