开发者

How to get JavaScriptSerializer to treat a sub-object as a plain old string?

I have JSON coming into my program like this:

{
    "Foo": "some string",
    "Bar": { "Quux" : 23 }
}

How can I use JavaScriptSerializer to parse this, but treat the Bar value as a string instead of a sub-object? The code below throws an exception, as expected.

After deserialization, I want thing.Bar to contain the string { "Quux" : 23 }. Is there a simple way to accomplish this?

class Thing
{
    public string Foo { get; set; }
    pub开发者_StackOverflow社区lic string Bar { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        string json = "{ \"Foo\": \"some string\", \"Bar\": { \"Quux\": 23 }}";
        var serializer = new JavaScriptSerializer();
        var thing = serializer.Deserialize<Thing>(json);
    }
}


You want to implement your own JavaScriptConverter to do this... here is an example...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web.Script.Serialization;
using System.Collections.ObjectModel;

namespace ConsoleApplication1
{
    [Serializable]
    public class Thing
    {
        public string Foo { get; set; }
        public string Bar { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var json = "{\"Foo\":\"some string\",\"Bar\":{\"Quux\":23}}";
            var serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(new JavaScriptConverter[] {
                new StringConverter()           
            });
            var thing = serializer.Deserialize<Thing>(json);

            Console.WriteLine(thing.Bar);
        }
    }

    public class StringConverter : JavaScriptConverter
    {
        public override IEnumerable<Type> SupportedTypes
        {
            get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(string) })); }
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            var i = dictionary.First();
            return "{ \"" + i.Key + "\" : " + i.Value + " }";
        }
    }
}


Have you tried the contents of Bar in quotes?

{
    "Foo": "some string",
    "Bar": "{ 'Quux' : 23 }"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜