Utf8Json icon indicating copy to clipboard operation
Utf8Json copied to clipboard

JsonSerializer.ToJsonString throws when one of the property of the object throws

Open Pvlerick opened this issue 5 years ago • 2 comments

 [Fact]
public void Test()
{
    var value = new MyObject();

    //throws
    Utf8Json.JsonSerializer.ToJsonString(value);
}

public class MyObject
{
    public string Value => throw new Exception();
}

Is there any way to customize the behaviour of the serializer so that this doesn't throw? For example, e.Message could be set as the value for that property.

Pvlerick avatar Jul 05 '19 13:07 Pvlerick

If you don't want to use [IgnoreDataMember] to completely ignore the member, you can probably use the ShouldSerializePattern for that: https://github.com/neuecc/Utf8Json#shouldserializexxx-pattern And in the ShouldSerializeValue method check if it throws an exception and return true/false appropriately.

Tornhoof avatar Jul 30 '19 12:07 Tornhoof

Well, the idea is not to have to mess with the objects that I want to serialize.

It's a bit of a deviated use of this library, but I'd like to use with NLog for structured logging, and in this case I don't know in advance which are the object that are going to be serialized.

Pvlerick avatar Aug 05 '19 09:08 Pvlerick