0

So I've made a custom JsonConverter that seems to do just perfectly serializing an object and deserializing it.

Specifically, I'm serializing an FFProbe output via NReco.VideoInfo:

public class NMediaInfoConverter : JsonConverter
{  
     public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    { 
        var n = ((MediaInfo) value).Result.CreateNavigator();
        n.MoveToRoot();
        var xDoc = new XmlDocument();
        xDoc.Load(n.ReadSubtree());

        writer.WriteRaw(JsonConvert.SerializeXmlNode(xDoc, serializer.Formatting)); 
    }

And if I serialize it thusly:

File.WriteAllText("myfile.json"), JsonConvert.SerializeObject(videoInfo, Formatting.Indented, new NMediaInfoConverter()));

Life is good. The files are perfect, and they deserialize without a problem.

Now if I make an encapsulating class, and decorate the property with the NMediaInfoConverter:

class MyMediaInfo
{
    [JsonConverter(typeof(NMediaInfoConverter))]
    public NReco.VideoInfo.MediaInfo NMediaInfo { get; set; }
}

At the very end of my JSON, I get an extra space, "null", a linefeed, and an extra closing bracket:

 null

}

Am I missing the point, somewhere?

Wesley Long
  • 1,708
  • 10
  • 20
  • 1
    This is probably a duplicate of [Token PropertyName in state Property would result in an invalid JSON object. when using custom `JsonConverter`](https://stackoverflow.com/q/54441810/3744182) in that you need to call `WriteRawValue()` instead of `WriteRaw()`. Can't say for sure without a [mcve]. – dbc Mar 20 '19 at 20:25
  • OK, from your answer it looks like `WriteRawValue()` was the answer. Shall I make this a duplicate then? – dbc Mar 20 '19 at 20:26
  • @dbc - You're absolutely correct. I found a blog post on the existence of this issue / bug / whatever in my answer below. Seeing this answer, though, makes it make more sense. Thank you. – Wesley Long Mar 20 '19 at 20:27
  • 1
    Yes, it's a duplicate. Not sure why I didn't find that answer in the searches I made. – Wesley Long Mar 20 '19 at 20:27
  • Probably because your code doesn't throw an exception, which was the symptom in the other question. – dbc Mar 20 '19 at 20:28
  • @dbc, oddly enough: After I made this post, I added another property "below" the one in my post, and it started throwing an exception, then. Prior to that, it had no problem writing invalid JSON to its output. – Wesley Long Mar 20 '19 at 20:29
  • 1
    Sometimes [`JsonWriter.AutoCompleteOnClose = true`](https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonWriter_AutoCompleteOnClose.htm) (which is [the default](https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonWriter.cs#L353)) can obscure bugs in JSON converters when the bug occurs writing the very last item in the file. – dbc Mar 20 '19 at 20:31
  • @dbc - Thanks! I'm going to remember that one! – Wesley Long Mar 20 '19 at 20:33

0 Answers0