如何将c#对象的某些字段序列化为JSON

时间:2014-07-01 18:42:46

标签: c# javascript json

所以说我们有这个对象

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

我将返回这些人员的列表,我需要将这些人物对象序列化为json格式。

我可以做到整个

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

但是我可以直接说出名字和姓氏,而不是序列化整个对象及其所有字段/属性吗?

1 个答案:

答案 0 :(得分:5)

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

如果您无法修改Person,则需要添加自定义转换器:

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; }
}