简体   繁体   中英

Serialize a part of an object to json

I have a class that looks like this in C#:

public class MyClass
{
    public string Id { get; set; }
    public string Description { get; set; }
    public string Location { get; set; }
    public List<MyObject> MyObjectLists { get; set; }
}

and i just want to serialize to JSON a part of that object : just Id , Description and Location properties so that the resulted JSON will look like this :

{
    "Id": "theID",
    "Description": "the description",
    "Location": "the location"
}

Is there a way to do it ?

If you use Newtonsoft Json.NET then you can apply [JsonIgnore] attribute to the MyObjectLists property.

public class MyClass
{
    public string Id { get; set; }
    public string Description { get; set; }
    public string Location { get; set; }

    [JsonIgnore]
    public List<MyObject> MyObjectLists { get; set; }
}

UPDATE #1

Yes, you can avoid [JsonIgnore] attribute. You may write a custom JsonConverter .

See example here: Custom JsonConverter

You can also use the ShouldSerialize solution from @GBreen12.

If you are using JSON.Net you can add a method:

public bool ShouldSerializeMyObjectList()
{
    return false;
}

Alternately you can use JsonIgnore above the properties you don't want to serialize but that will also stop them from being deserialized.

EDIT:

JSON.Net automatically looks for a method with signature public bool ShouldSerializeProperty() and uses that as logic for whether it should serialize a particular property. Here is the documentation for that:

https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm

Here is an example:

static void Main(string[] args)
{
    var thing = new MyClass
    {
        Id = "ID",
        Description = "Description",
        Location = "Location",
        MyObjectLists = new List<MyObject>
        {
            new MyObject { Name = "Name1" },
            new MyObject { Name = "Name2" }
        }
    };

    var json = JsonConvert.SerializeObject(thing);
    Console.WriteLine(json);
    Console.Read();
}

class MyClass
{
    public string Id { get; set; }
    public string Description { get; set; }
    public string Location { get; set; }
    public List<MyObject> MyObjectLists { get; set; }

    public bool ShouldSerializeMyObjectLists()
    {
        return false;
    }
}

class MyObject
{
    public string Name { get; set; }
}

The JSON output looks like this: {"Id":"ID","Description":"Description","Location":"Location"}

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