1

Is there a way you can specify what properties to include when using JSON serialize?

I'd like to do something like this:

var string = JSON.serialize(myObject, ["includedProperty1", "includedProp2"]);

Here's documentation on how to ignore properties:

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-ignore-properties?pivots=dotnet-5-0

It says to use Json Ignore metadata but my model has about 50 different fields. It may have more.

So, I'd like to ignore all properties except a few or do I have to use [JSonIgnore] for all the properties?

Here's what I have so far:

using System.Text.Json;

string fileName = "project.json";
var options = new JsonSerializerOptions() { };

var isValid = NSJsonSerialization.IsValidJSONObject(model);

// error on this line
string value = JsonSerializer.Serialize(model);

The gives an error:

A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.

Here's what I've tried for that error:

var options = new JsonSerializerOptions() { };
options.ReferenceHandler = "Ignore"; // not allowed value
1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231
  • 1
    `JsonIgnore` needs .NET 5.0 or .NET Core 3.0 https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonignoreattribute?view=net-5.0 – Akshay G Jun 08 '21 at 05:11
  • I just added using System.Text.Json.Serialization; and JsonIgnore is not showing error – 1.21 gigawatts Jun 08 '21 at 05:12
  • Check this out ... https://stackoverflow.com/questions/59199593/net-core-3-0-possible-object-cycle-was-detected-which-is-not-supported – Akshay G Jun 08 '21 at 05:27
  • @AkshayGaonkar Interesting. It looks like there is a flag I can set to ignore references but it's giving me an error. var options = new JsonSerializerOptions() { }; options.ReferenceHandler = "Ignore"; – 1.21 gigawatts Jun 08 '21 at 05:35
  • That's for Newtonsoft.Json Try the one which is applicable for System.Text.Json `options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;`. Do check what's the consequence of doing it too – Akshay G Jun 08 '21 at 05:43
  • @AkshayGaonkar still getting an error when running serialize – 1.21 gigawatts Jun 08 '21 at 06:27
  • you are creating the options but not using while serializing `string value = JsonSerializer.Serialize(model,options);` – Akshay G Jun 11 '21 at 08:22

1 Answers1

3

There is no 'opt-in' logic as far as I know.

But since you said "a few" there is an easy trick, using an ad-hoc anonymous type:

var s = JsonSerializer.Serialize(
    new { myObject.includedProperty1, myObject.includedProp2 });

...

var otherObject = JsonSerializer.Deserialize<OrignalType>(s);
H H
  • 263,252
  • 30
  • 330
  • 514