1

Suppose I have a object structure like this

Library 1 ---- 1+ Book 1 ---- 1+ Page

I want to serialize a json object of a book with an array of page objects.

Using JSON.net serializer, I can get this to serialize without getting a circular reference, but the JSON still includes all of the properties of the book in each page, which includes data about the library...which can have data on other books which is a ton of noise.

From the answer from this question - Serialize Entity Framework objects into JSON, I know that I can do generics, but is this really the only way? This just seems like a ton of extra work. Especially if for a Json result that is Book with and array of page objects in it.

I am using Entity Framework 4.3.1 and Json.net 4.0.30319...

Community
  • 1
  • 1
Ben Jones
  • 2,101
  • 1
  • 26
  • 36

1 Answers1

3

You should look at the serialization attributes.

[JsonObject(MemberSerialization.OptIn)]
public class Page
{
    [JsonProperty]
    public string Text { get; set; }

    // not serialized because mode is opt-in
    public Book Book { get; set; }
}

Original answer

The aforementioned way should be prefered in most of the cases, but there are some where it is not enough.

There are two ways of doing it.

You can implement a JsonConverter, and override the WriteJson method to write only the properties you want.

class BookConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Book);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value.GetType() == typeof(T2))
        {
            JObject obj = new JObject();
            Book b = value as Book;
            obj["titre"] = b.Name;
            obj["pages"] = b.Pages;
            // This line can also be 
            // obj.WriteTo(writer, this);
            // if you also need change the way pages are serialized.
            obj.WriteTo(writer, null);
        }
        else
        {
            throw new NotImplementedException();
        }
    }
}

You can call it like that :

string result = JsonConvert.SerializeObject(
    book,
    new JsonSerializerSettings
    {
        Converters = new JsonConverter[] { new BookConverter() }
    });

You can also create a JsonBook class, and serialize it.

class JsonBook{
    public JsonBook(Book b){/*...*/}
    public List<Pages> l;
    public string title;
    // No reference to Library.
}
Clement Bellot
  • 841
  • 1
  • 7
  • 19