Use Attr tags for json?

I ask this question , and I'm wondering if a possible solution is to add attribute tags to say that the object [] [] maps to MyType [], where element 1 is MyType.IntName and element 2 is MyType.HtmlSz

Is this possible in any json solution on .NET?

0
source share
1 answer

This is possible when using JavaScriptConverter. You must define the class MyTypeas follows:

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

and class MyTypeConverterlike

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

You can then convert your input with respect to the following simple code:

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

Source: https://habr.com/ru/post/1758905/


All Articles