Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.NET - How to exclude properties from Serialization without access to class

I am trying to serialize a class using Json.NET. Here's what I do for the moment.

public class AClass
{
    // I don't have access to BClass
    public BClass b;
}

AClass a = new AClass();
JsonConvert.SerializeObject(a);

I don't have access to BClass. I want to serialize my AClass but I don't want to serialize all properties of BClass, only some of them.

How can I do that ?

like image 688
MaT Avatar asked Dec 24 '22 20:12

MaT


2 Answers

You can use a custom ContractResolver, this library will make it easier to build.

var propertiesContractResolver = new PropertiesContractResolver();
propertiesContractResolver.ExcludeProperties.Add("BClass.Id");
var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = propertiesContractResolver;
JsonConvert.SerializeObject(a, serializerSettings);
like image 68
Cheng Chen Avatar answered Dec 28 '22 05:12

Cheng Chen


Couple of ideas come to mind, which you can choose from depending on how many distinct classes you need to do this for and how performant you need the algorithm to be:

Probably the fastest would be to use Json.net's custom converters or Contract Resolvers and build one that suits your needs, i.e. ignores properties you don't want included.

Another approach would be to map this class to another similarly-defined class that simply doesn't contain the properties you don't want included, and then serialize that class. You can use AutoMapper for quick mapping between similarly-defined classes.

Finally, you can create an ExpandoObject (or even a Dictionary<string, object>) and add the properties that you want included into the Expando or the Dictionary (and you can copy those properties/key-value pairs either manually or by reflection, etc.) and then serialize that object/dictionary.

like image 34
Arash Motamedi Avatar answered Dec 28 '22 05:12

Arash Motamedi