3

Possible Duplicate:
Using Json.net - partial custom serialization of a c# object

I have a class that I successfully get to serialize in json.net when using asp.net MVC 4 WebAPI. The class has a property that is a list of strings.

public class FruitBasket {
    [DataMember]
    public List<string> FruitList { get; set; }

    public int FruitCount {
        get {
            return FruitList.Count();
        }
    }
}

In my Get method the serialization happens ok and I get an empty array i.e. [] for the FruitList property in my JSON. If I use the same json in a PUT request's body I get an error in the FruitCount property during deserialization because FruitList is null.

I want the FruitList property (basically my get only properties) to serialize but not deserialize. Is it possible with a setting or other wise with json.net?

1
  • Just a quick question.. You are aware that Serialization is the process of flattening an code/object hiearchy? From that point of view, you can't really serialize a property, because it's only a method. Did you serialize the field behind the property or am I not understanding correctly the question? Commented Oct 23, 2012 at 20:45

1 Answer 1

0

I realize this does not answer your question, but addresses the error being generated so might make worrying about custom serialization irrelevant

use a private variable for FruitList, return it in the get and in set, if value is null then set the private variable equal to a new list.

public class FruitBasket
{
    private List<string> _fruitList;

    [DataMember]
    public List<string> FruitList
    {
        get
        {
            return _fruitList;
        }
        set
        {
            if (value == null)
            {
                _fruitList = new List<string>();
            }
            else
            {
                _fruitList = value;
            }
        }
    }

    public int FruitCount
    {
        get
        {
            return FruitList.Count();
        }
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.