1

I am serializing objects to json using Json.NET. However, certain properties of my object are objects themselves that contain quite a lot of additional information, so my json output is very cluttered and hard to interpret. Ideally, I would like to show that these specific properties exist (show the object type) but without fully serializing them.

For example, instead of:

{
    "sport": "football",
    "popular": true,
    "rules": [
        {
            "highSchool": 
            {
                ...
            }
        },
        {
            "college":
            {
                ...
            }
        },
        {
            "nfl":
            {
                ...
            }
        }
    ]
}

I would like to show:

{
    "sport": "football",
    "popular": true,
    "rules": {Sports.Football.Rules}
}

Is this possible? I have tried using [JsonIgnore] in my Rules class for the rules property, but this ignores the rules property entirely instead of including but not serializing the property's object. I also read that [JsonProperty] and [JsonIgnore] are static and cannot be conditionally set, so that seems to rule out an alternative approach of selectively serializing the property (such as if Verbose is provided).

BlueTriangles
  • 1,124
  • 2
  • 13
  • 26
  • 1
    Possible duplicate of [custom serializer for just one property in Json.NET](https://stackoverflow.com/questions/18521970/custom-serializer-for-just-one-property-in-json-net) – devNull Aug 09 '19 at 23:35
  • You could do what you'd like to by using a custom serializer for the property as described in the above post. However, by serializing `rules` to simply the name of the type, you probably wouldn't have any way to deserialize the json – devNull Aug 09 '19 at 23:39
  • 1
    I would use the `ToStringConverter` from [How to make JSON.Net serializer to call ToString() when serializing a particular type?](https://stackoverflow.com/q/22354867/10263). You can mark any properties you want with `[JsonConverter(typeof(ToStringConverter))]` to get them to use the converter. The default implementation of `ToString()` will write out the type name for a class. If you want a different output, you can override `ToString()` to make it write whatever string value you want. – Brian Rogers Aug 09 '19 at 23:48

0 Answers0