1

I am using C# .NET 4.0 and Newtonsoft JSON 4.5.0.11

    [JsonObject(MemberSerialization.OptIn)]
    public interface IProduct
    {
        [JsonProperty(PropertyName = "ProductId")]
        int Id { get; set; }
        [JsonProperty]
        string Name { get; set; }
    }

    public abstract class BaseEntity<T>
    {
        private object _id;

        public T Id
        {
            get { return (T)_id; }
            set { _id = value; }
        }
    }

    public class Product : BaseEntity<int>, IProduct
    {
        public string Name { get; set; }
        public int Quantity { get; set; }
    }

I need to serialize part of object and I use interfaces with declared concrete properties to do this.

The serialization looks like:

Product product = new Product { Id = 1, Name = "My Product", Quantity = 5};
JsonConvert.SerializeObject(product);

Expected result is:

{"ProductId": 1, "Name": "My Product"}

But actual result is:

{"Name": "My Product"}

How can I serialize this object correctly?


UPD: Looked at the source code of json.net and came to the conclusion that this is a bug with grab information about object through ReflectionUtils.

1 Answer 1

1

Have you tried this?

public interface IProduct
{
    int Id { get; set; }
    string Name { get; set; }
}

[JsonObject(MemberSerialization.OptIn)]
public abstract class BaseEntity<T>
{
    private object _id;
    [JsonProperty]
    public T Id
    {
        get { return (T)_id; }
        set { _id = value; }
    }
}

[JsonObject(MemberSerialization.OptIn)]
public class Product : BaseEntity<int>, IProduct
{
    [JsonProperty]
    public string Name { get; set; }
    [JsonProperty]
    public int Quantity { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I wouldn't want to use JsonProperty and JsonObject in a base class, because it placed in another project (library), which doesn't have reference to Newtonsoft JSON dll.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.