为json使用Attr标签?

时间:2010-07-12 07:28:33

标签: .net json

have this question我想知道一个可能的解决方案是否可以添加属性标签来说明对象[] []映射到MyType [],其中元素1是MyType.IntName,元素2是MyType.HtmlSz < / p>

在.NET上的任何json解决方案中都可以吗?

1 个答案:

答案 0 :(得分:1)

可以使用JavaScriptConverter。您应该定义类MyType,如下所示:

public class MyType {
    public string IntName { get; set; }
    public int HtmlSz1 { get; set; }
    public int HtmlSz2 { get; set; }
}

和班级MyTypeConverter一样

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

    public override object Deserialize (IDictionary<string, object> dictionary,
                                      Type type, JavaScriptSerializer serializer) {
        if (dictionary == null)
            throw new ArgumentNullException ("dictionary");

        if (type == typeof (MyType[])) {
            ArrayList itemsList = (ArrayList)dictionary["resources"];
            MyType[] res = new MyType[itemsList.Count];
            for (int i = 0; i < itemsList.Count; i++) {
                ArrayList entry = (ArrayList)itemsList[i];
                res[i] = new MyType () {
                    HtmlSz1 = (int)entry[0],
                    HtmlSz2 = (int)entry[1],
                    IntName = (string)entry[2]
                };
            }
            return res;
        }
        return null;
    }

    public override IDictionary<string, object> Serialize (object obj,
                                                 JavaScriptSerializer serializer) {
        throw new InvalidOperationException ("We only Deserialize");
    }
}

然后,您可以根据以下简单代码转换输入数据:

JavaScriptSerializer serializer = new JavaScriptSerializer ();
serializer.RegisterConverters (new JavaScriptConverter[] { new MyTypeConverter () });
MyType[] res = serializer.Deserialize<MyType[]> (
    @"{""resources"": [[123,567,""<div ...""],[456,789,""<table ...""]]}");