This project has moved. For the latest updates, please go here.

Attributes don't get serialized - but why?

Aug 7, 2012 at 9:25 PM

Hi,

I have two applications sharing the same code base. One application is a web application (ASP.Net MVC3), which has some sort of API to accept JSON-Serialized data. The other application is a client-application that makes requests to the web application to submit such data.

I have defined an entity "Game":

 

public class Game : Entity
{
    public string Name { get; set; }
    public string Shortcut { get; set; }
}

 

When I submit my data, I am basically doing following

using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
    streamWriter.Write(JsonConvert.SerializeObject(entity));
}

where "entity" is an instance of "Game". However - the serialized string is something like:

{"Id":"50203b74d808524694b8e184"}

Where are my other attributes gone? If "Game" does not inherit from "Entity", serialization works fine (in terms of: "Name" and "Shortcut" are now present in the serialized string).

Coordinator
Aug 11, 2012 at 8:37 PM

Hi,

Sorry for the late reply, I was on holiday. I will look into your question soon (hopefully this week sometime).

Coordinator
Aug 17, 2012 at 12:14 AM

I have found two ways to fix this:

Either use this:

    [JsonObject(MemberSerialization.OptOut)]
    public class Game : Entity
    {
        public string Name { get; set; }
        public string Shortcut { get; set; }
    }

Or use this:

    public class Game : Entity
    {
        [JsonProperty]
        public string Name { get; set; }
        [JsonProperty]
        public string Shortcut { get; set; }
    }

I am not very familiar with JSON.Net so there might be other ways to fix this; I noticed JsonSerializerSettings which might be able to influence the serialization process but didn't find a setting there to get the desired output. Also implementing your own JsonConverter (or CustomCreationConverter<T>) looks promising for finer grained control on the (de)serialization process but is also more work.