如何让JavaScriptSerializer将子对象视为普通的旧字符串?

时间:2011-02-17 16:21:47

标签: c# .net json serialization json.net

我有JSON进入我的程序:

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

如何使用JavaScriptSerializer解析此,但将条形值视为字符串而不是子对象?正如预期的那样,下面的代码会引发异常。

反序列化后,我希望thing.Bar包含字符串 { "Quux" : 23 }。 有没有一种简单的方法来实现这一目标?

class Thing
{
    public string Foo { get; set; }
    public 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);
    }
}

2 个答案:

答案 0 :(得分:1)

您想要实现自己的JavaScriptConverter来执行此操作...这是一个示例...

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 + " }";
        }
    }
}

答案 1 :(得分:0)

您是否在引号中尝试过Bar的内容?

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