loo*_*uni 1 javascript c# json
所以说我们有这个对象
public class Person{
public string firstName { get; set; }
public string lastName { get; set; }
public DateTime dob { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我将返回这些人员列表,我需要将这些人物对象序列化为json格式.
我可以做到整体
using System.Web.Script.Serialization;
...
var peopleList = new List<Person> { person_1, person_2 }
var jsonPeople = new JavaScriptSerializer().Serialize(peopleList);
return jsonPeople
Run Code Online (Sandbox Code Playgroud)
但是我可以只说出名字和姓氏而不是序列化整个对象及其所有字段/属性吗?
[ScriptIgnore]
public DateTime dob { get; set; }
Run Code Online (Sandbox Code Playgroud)
如果无法编辑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; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |