当前位置:  开发笔记 > 编程语言 > 正文

使用DataContractJsonSerializer将数组值反序列化为.NET属性

如何解决《使用DataContractJsonSerializer将数组值反序列化为.NET属性》经验,为你挑选了1个好方法。

我正在使用Silverlight 4中的DataContractJsonSerializer,并希望反序列化以下JSON:

{
    "collectionname":"Books",
    "collectionitems": [
            ["12345-67890",201,
             "Book One"],
            ["09876-54321",45,
             "Book Two"]
        ]
}

进入以下类:

class BookCollection
{
  public string collectionname { get; set; }
  public List collectionitems { get; set; }
}

class Book
{
  public string Id { get; set; }
  public int NumberOfPages { get; set; }
  public string Title { get; set; }
}

扩展DataContractJsonSerializer以将"collectionitems"中未命名的第一个数组元素映射到Book类的Id属性,NumberOfPages属性的第二个元素和Title的最终元素是什么?我无法控制此实例中的JSON生成,并希望该解决方案能够与.NET的Silverlight子集一起使用.如果解决方案也可以执行相反的序列化,那将是很好的.



1> Justin Grant..:

如果这不是Silverlight中,你可以使用IDataContractSurrogate使用object[](什么在你的JSON实际存在),而不是Book序列化时/反序列化.遗憾的是,IDataContractSurrogate(以及DataContractJsonSerializer使用它的构造函数的重载)在Silverlight中不可用.

在Silverlight上,这是一个hacky但简单的解决方法.Book从一个imlpements类型派生类ICollection.由于序列化JSON中的类型是object[],框架将尽职尽责地将其序列化为您的ICollection,然后您可以使用您的属性进行包装.

最简单(也是最讨厌的)只是来源于List.这种简单的黑客行为有一个缺点,即用户可以修改基础列表数据并弄乱您的属性.如果您是此代码的唯一用户,那可能没问题.通过更多的工作,您可以滚动自己的实现,ICollection并且只允许运行序列化工作的足够方法,并为其余部分抛出异常.我在下面列出了两种方法的代码示例.

如果上面的黑客对你来说太难看了,我相信有更优雅的方法可以解决这个问题.你可能会想你的注意力集中于创建一个自定义集合类型,而不是List你的collectionitems财产.此类型可以包含类型的字段List(这是JSON中的实际类型),您可以说服序列化程序填充.然后,您的IList实现可以将该数据挖掘到实际的Book实例中.

另一行调查可能会尝试进行转换.例如,您可以在Book和之间实现隐式类型转换,string[]并且序列化是否足够智能以使用它?我对此表示怀疑,但值得一试.

无论如何,这里是上面提到的从ICollection导入的代码示例.警告:我还没有在Silverlight上验证这些,但他们应该只使用Silverlight可访问的类型,所以我认为(手指交叉!)它应该工作正常.

简单,Hackier示例

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;

[DataContract]
class BookCollection
{
    [DataMember(Order=1)]
    public string collectionname { get; set; }

    [DataMember(Order = 2)]
    public List collectionitems { get; set; }
}

[CollectionDataContract]
class Book : List
{
    public string Id { get { return (string)this[0]; } set { this[0] = value; } }
    public int NumberOfPages { get { return (int)this[1]; } set { this[1] = value; } }
    public string Title { get { return (string)this[2]; } set { this[2] = value; } }

}

class Program
{
    static void Main(string[] args)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BookCollection));
        string json = "{"
                    + "\"collectionname\":\"Books\","
                    + "\"collectionitems\": [ "
                            + "[\"12345-67890\",201,\"Book One\"],"
                            + "[\"09876-54321\",45,\"Book Two\"]"
                        + "]"
                    + "}";

        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            BookCollection obj = ser.ReadObject(ms) as BookCollection;
            using (MemoryStream ms2 = new MemoryStream())
            {
                ser.WriteObject(ms2, obj);
                string serializedJson = Encoding.UTF8.GetString(ms2.GetBuffer(), 0,  (int)ms2.Length);
            }
        }
    }
}


更难,更少hacky样本

这是第二个示例,显示ICollection的手动实现,它阻止用户访问集合 - 它支持调用Add()3次(在反序列化期间)但不允许通过修改ICollection.使用显式接口实现公开ICollection方法,并且这些方法有一些属性可以将它们隐藏在智能感知中,这应该会进一步降低黑客因素.但是你可以看到这是更多的代码.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;

[DataContract]
class BookCollection
{
    [DataMember(Order=1)]
    public string collectionname { get; set; }

    [DataMember(Order = 2)]
    public List collectionitems { get; set; }
}

[CollectionDataContract]
class Book : ICollection
{
    public string Id { get; set; }
    public int NumberOfPages { get; set; }
    public string Title { get; set; }

    // code below here is only used for serialization/deserialization

    // keeps track of how many properties have been initialized
    [EditorBrowsable(EditorBrowsableState.Never)]
    private int counter = 0;

    [EditorBrowsable(EditorBrowsableState.Never)]
    public void Add(object item)
    {
        switch (++counter)
        {
            case 1:
                Id = (string)item;
                break;
            case 2:
                NumberOfPages = (int)item;
                break;
            case 3:
                Title = (string)item;
                break;
            default:
                throw new NotSupportedException();
        }
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    IEnumerator System.Collections.Generic.IEnumerable.GetEnumerator() 
    {
        return new List { Id, NumberOfPages, Title }.GetEnumerator();
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 
    {
        return new object[] { Id, NumberOfPages, Title }.GetEnumerator();
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    int System.Collections.Generic.ICollection.Count 
    { 
        get { return 3; } 
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    bool System.Collections.Generic.ICollection.IsReadOnly 
    { get { throw new NotSupportedException(); } }

    [EditorBrowsable(EditorBrowsableState.Never)]
    void System.Collections.Generic.ICollection.Clear() 
    { throw new NotSupportedException(); }

    [EditorBrowsable(EditorBrowsableState.Never)]
    bool System.Collections.Generic.ICollection.Contains(object item) 
    { throw new NotSupportedException(); }

    [EditorBrowsable(EditorBrowsableState.Never)]
    void System.Collections.Generic.ICollection.CopyTo(object[] array, int arrayIndex) 
    { throw new NotSupportedException(); }

    [EditorBrowsable(EditorBrowsableState.Never)]
    bool System.Collections.Generic.ICollection.Remove(object item) 
    { throw new NotSupportedException(); }
}

class Program
{
    static void Main(string[] args)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BookCollection));
        string json = "{"
                    + "\"collectionname\":\"Books\","
                    + "\"collectionitems\": [ "
                            + "[\"12345-67890\",201,\"Book One\"],"
                            + "[\"09876-54321\",45,\"Book Two\"]"
                        + "]"
                    + "}";

        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            BookCollection obj = ser.ReadObject(ms) as BookCollection;
            using (MemoryStream ms2 = new MemoryStream())
            {
                ser.WriteObject(ms2, obj);
                string serializedJson = Encoding.UTF8.GetString(ms2.GetBuffer(), 0,  (int)ms2.Length);
            }
        }
    }
}



顺便说一句,我第一次阅读你的问题时,我跳过了重要的Silverlight要求.哎呀!无论如何,如果不使用Silverlight,这就是我为这种情况编写的解决方案 - 它更容易,我也可以将它保存在以后的任何Google员工中.

您正在寻找的(在常规的.NET框架上,而不是Silverlight上)魔术是IDataContractSurrogate.如果要在序列化/反序列化时将一种类型替换为另一种类型,请实现此接口.在你的情况wnat替代object[]Book.

以下是一些显示其工作原理的代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Collections.ObjectModel;

[DataContract]
class BookCollection
{
    [DataMember(Order=1)]
    public string collectionname { get; set; }

    [DataMember(Order = 2)]
    public List collectionitems { get; set; }
}

class Book 
{ 
  public string Id { get; set; } 
  public int NumberOfPages { get; set; } 
  public string Title { get; set; } 
} 

// A type surrogate substitutes object[] for Book when serializing/deserializing.
class BookTypeSurrogate : IDataContractSurrogate
{
    public Type GetDataContractType(Type type)
    {
        // "Book" will be serialized as an object array
        // This method is called during serialization, deserialization, and schema export. 
        if (typeof(Book).IsAssignableFrom(type))
        {
            return typeof(object[]);
        }
        return type;
    }
    public object GetObjectToSerialize(object obj, Type targetType)
    {
        // This method is called on serialization.
        if (obj is Book)
        {
            Book book = (Book) obj;
            return new object[] { book.Id, book.NumberOfPages, book.Title };
        }
        return obj;
    }
    public object GetDeserializedObject(object obj, Type targetType)
    {
        // This method is called on deserialization.
        if (obj is object[])
        {
            object[] arr = (object[])obj;
            Book book = new Book { Id = (string)arr[0], NumberOfPages = (int)arr[1], Title = (string)arr[2] };
            return book;
        }
        return obj;
    }
    public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
    {
        return null; // not used
    }
    public System.CodeDom.CodeTypeDeclaration ProcessImportedType(System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit)
    {
        return typeDeclaration; // Not used
    }
    public object GetCustomDataToExport(Type clrType, Type dataContractType)
    {
        return null; // not used
    }
    public object GetCustomDataToExport(System.Reflection.MemberInfo memberInfo, Type dataContractType)
    {
        return null; // not used
    }
    public void GetKnownCustomDataTypes(Collection customDataTypes)
    {
        return; // not used
    }
}


class Program
{
    static void Main(string[] args)
    {
        DataContractJsonSerializer ser  =
            new DataContractJsonSerializer(
                typeof(BookCollection), 
                new List(),        /* knownTypes */
                int.MaxValue,            /* maxItemsInObjectGraph */ 
                false,                   /* ignoreExtensionDataObject */
                new BookTypeSurrogate(),  /* dataContractSurrogate */
                false                    /* alwaysEmitTypeInformation */
                );
        string json = "{"
                    + "\"collectionname\":\"Books\","
                    + "\"collectionitems\": [ "
                            + "[\"12345-67890\",201,\"Book One\"],"
                            + "[\"09876-54321\",45,\"Book Two\"]"
                        + "]"
                    + "}";

        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            BookCollection obj = ser.ReadObject(ms) as BookCollection;
            using (MemoryStream ms2 = new MemoryStream())
            {
                ser.WriteObject(ms2, obj);
                string serializedJson = Encoding.UTF8.GetString(ms2.GetBuffer(), 0,  (int)ms2.Length);
            }
        }
    }
}

推荐阅读
mobiledu2402851377
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有