How to inherit the attribute from interface to object when serializing it using JSON.NET

May 10, 2011 at 3:38 PM

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json.Serialization;
using System.Linq;
using System.Reflection;
public interface IParent
{
    [JsonProperty]
    int Id {get;set;}
}

[JsonObject(MemberSerialization.OptIn)]
public class Parent : IParent
{
    public int Id { get;set; }  
    public string Name {get;set;}   
}

public class Serializer
{
    public static void Main()
    {

        var parent = new Parent() { Id = 1, Name ="Parent"};        
        var sb = new StringBuilder();
                var sw = new StringWriter(sb);

                var settings = new JsonSerializerSettings()
                       {
                           NullValueHandling = NullValueHandling.Ignore                            
                       };

            var output = JsonConvert.SerializeObject(parent, Formatting.None, settings);
                Console.WriteLine(output);
            Console.ReadKey();
    }
}

In the above code, the output is {}. Is it possible to serialize and get the output as {"Id":1}?

May 13, 2011 at 8:18 AM

Just seen this discussion post, I've also reported this and issue tracker.  Slightly different context but same issue of Json attributes not being read off the inherited interface.  I've downloaded / stepped through the code.  If I get chance I may try to see if I can implement the feature and supply a patch.

See http://json.codeplex.com/workitem/20749