使用JavaScriptSerializer进行序列化时,是否可以忽略该类的某些字段?
使用JavaScriptSerializer进行序列化时,我们可以更改字段的名称吗?例如,字段是字符串is_OK,但我想将它映射到isOK?
Joh*_*han 12
您可以使用[ScriptIgnore]跳过属性:
using System;
using System.Web.Script.Serialization;
public class Group
{
// The JavaScriptSerializer ignores this field.
[ScriptIgnore]
public string Comment;
// The JavaScriptSerializer serializes this field.
public string GroupName;
}
Run Code Online (Sandbox Code Playgroud)
对于最大的灵活性(因为你提到的名字一样),理想的是要调用RegisterConverters
的上JavaScriptSerializer
对象,注册一个或多个JavaScriptConverter
实现(也许在一个数组或迭代器块).
然后,您可以Serialize
通过向返回的字典添加键/值对来实现以任何名称添加(或不添加)和值.如果数据是双向的,您还需要匹配Deserialize
,但通常(对于ajax服务器)这不是必需的.
完整示例:
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
class Foo
{
public string Name { get; set; }
public bool ImAHappyCamper { get; set; }
private class FooConverter : JavaScriptConverter
{
public override object Deserialize(System.Collections.Generic.IDictionary<string, object> dictionary, System.Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override System.Collections.Generic.IEnumerable<System.Type> SupportedTypes
{
get { yield return typeof(Foo); }
}
public override System.Collections.Generic.IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var data = new Dictionary<string, object>();
Foo foo = (Foo)obj;
if (foo.ImAHappyCamper) data.Add("isOk", foo.ImAHappyCamper);
if(!string.IsNullOrEmpty(foo.Name)) data.Add("name", foo.Name);
return data;
}
}
private static JavaScriptSerializer serializer;
public static JavaScriptSerializer Serializer {
get {
if(serializer == null) {
var tmp = new JavaScriptSerializer();
tmp.RegisterConverters(new [] {new FooConverter()});
serializer = tmp;
}
return serializer;
}
}
}
static class Program {
static void Main()
{
var obj = new Foo { ImAHappyCamper = true, Name = "Fred" };
string s = Foo.Serializer.Serialize(obj);
}
}
Run Code Online (Sandbox Code Playgroud)