loonyuni
loonyuni

Reputation: 1473

How to serialize certain fields of a c# object to JSON

So say we have this object

public class Person{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public DateTime dob { get; set; }
}

and I am going to return a List of these Persons, and I need to serialize these person objects into json format.

I can do the whole

using System.Web.Script.Serialization;
...
var peopleList = new List<Person> { person_1, person_2 }
var jsonPeople = new JavaScriptSerializer().Serialize(peopleList);
return jsonPeople

BUT is it possible for me to just get say the first and last name instead of serializing the whole object and all of it's fields/properties?

Upvotes: 1

Views: 245

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062865

[ScriptIgnore]
public DateTime dob { get; set; }

If you can't edit Person, you need to add a custom converter:

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

static class Program
{
    static void Main()
    {
        var ser = new JavaScriptSerializer();
        ser.RegisterConverters(new[] { new PersonConverter() });
        var person = new Person
        {
            firstName = "Fred",
            lastName = "Jones",
            dob = new DateTime(1970, 1, 1)
        };
        var json = ser.Serialize(person);
        Console.WriteLine(json);
    }
}

class PersonConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get { yield return typeof(Person); }
    }
    public override IDictionary<string, object> Serialize(
        object obj, JavaScriptSerializer serializer)
    {
        var person = (Person)obj;
        return new Dictionary<string, object> {
            {"firstName", person.firstName },
            {"lastName", person.lastName }
        };
    }
    public override object Deserialize(
        IDictionary<string, object> dictionary, Type type,
        JavaScriptSerializer serializer)
    {
        object tmp;
        var person = new Person();
        if (dictionary.TryGetValue("firstName", out tmp))
            person.firstName = (string)tmp;
        if (dictionary.TryGetValue("lastName", out tmp))
            person.lastName = (string)tmp;
        return person;
    }
}

public class Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public DateTime dob { get; set; }
}

Upvotes: 5

Related Questions