使用JavaScriptSerializer进行序列化时,是否可以忽略该类的某些字段?
使用JavaScriptSerializer进行序列化时,我们可以更改字段的名称吗? 例如,字段是字符串is_OK,但我希望它映射到isOK?
答案 0 :(得分: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;
}
答案 1 :(得分:6)
为了获得最大的灵活性(因为你也提到了名字),理想的做法是在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);
}
}
答案 2 :(得分:0)
我会使用匿名类型来保持生成的JSON清洁。
class SomeClass {
public string WantedProperty { get; set; }
public string UnwantedProperty { get; set; }
}
var objects = new List<SomeClass>();
...
new JavaScriptSerializer().Serialize(
objects
.Select(x => new {
x.WantedProperty
}).ToArray()
);