如何将c#对象的特定字段序列化为JSON

本文关键字:字段 序列化 JSON 对象 | 更新日期: 2023-09-27 18:10:57

假设我们有这个对象

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

但是是否有可能让我只说名字和姓氏,而不是序列化整个对象和它的所有字段/属性?

如何将c#对象的特定字段序列化为JSON

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