Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
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? –  LightStriker Oct 23 '12 at 20:45
add comment

marked as duplicate by Erik Philips, Lol4t0, Aleks G, skolima, Eitan T Oct 24 '12 at 9:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

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();
        }
    }
} 
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.