Some questions regarding JavaScriptSerializer
When using JavaScriptSerializer to do serialization, can some of the field of the class be ignored?
When using JavaScriptS开发者_如何学编程erializer to do serialization, can we changes the name of the field? For example, the field is string is_OK, but I want it be mapped to isOK?
You can use [ScriptIgnore] to skip a property:
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;
}
For the most flexibility (since you mention names as well), the ideal thing is to call RegisterConverters
on the JavaScriptSerializer
object, registering one or more JavaScriptConverter
implementations (perhaps in an array or iterator block).
You can then implement Serialize
to add (or not) and values under any names, by adding key/value pairs to the dictionary that you return. If the data is bidirectional you will also need a matching Deserialize
, but often (for ajax servers) this is not required.
Full example:
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);
}
}
I would use anonymous types to keep the resulting JSON clean.
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()
);
精彩评论