4

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 ?

afuzzyllama
  • 6,538
  • 5
  • 47
  • 64
MaT
  • 1,556
  • 3
  • 28
  • 64
  • 1
    Take a look at the accepted answer of this question: http://stackoverflow.com/questions/13588022/exclude-property-from-serialization-via-custom-attribute-json-net – Peter Bons Feb 09 '17 at 10:04

2 Answers2

9

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);
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
  • 1
    You have to add a dependency on a nuget package just to not serialize a field ? – Bidou Feb 09 '17 at 10:15
  • I don't see a problem with this. You can always copy the source or write your own if you do not like nuget. – Alek Davis Jun 08 '19 at 06:25
  • This nuget package very helpful as I had two different serialization needs for the same object. Unusual, yes. This was perfect. Works great, too. – Bill Noel Oct 18 '19 at 20:05
1

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.

Arash Motamedi
  • 9,284
  • 5
  • 34
  • 43