Alex Rivera | Logout

Can Json.NET populate readonly fields in a class?

Asked 2010-11-14T19:01:46.633
13

I haven't seen much information about Json.NET supporting deserializing objects with readonly fields. I do notice that the .NET DataContract and DataMember attributes allow for populating readonly fields during deserializtion, but Json.NET doesn't seem to support this, at least from the behavior I'm seeing.

Edit
Report

1 Answer

-2

afai can see changing a field to readonly results in a null value after deserialization. I had a working sample for another question (modified as shown below), and that's the behaviour I see.

public class NameAndId
{
    public string name;
    public int id; 
}

public class Data
{
    public NameAndId[] data;
}

public class Target
{
    public string id;
    public readonly NameAndId from;
    public DateTime updated_time;
    public readonly string message;
    public Data likes;
}

public class Program
{
    static void Main(string[] args)
    {
        string json = File.ReadAllText(@"c:\temp\json.txt");
        Target newTarget = JsonConvert.DeserializeObject<Target>(json);
    }
}
answered 2010-11-14T21:05:07.420

Your Answer