简体   繁体   中英

Some questions regarding JavaScriptSerializer

  1. When using JavaScriptSerializer to do serialization, can some of the field of the class be ignored?

  2. When using JavaScriptSerializer 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()
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM