1.21 gigawatts
1.21 gigawatts

Reputation: 17806

Is there a way to serialize an object to JSON but only include a few properties?

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

Upvotes: 1

Views: 1737

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273464

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);

Upvotes: 3

Related Questions