gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:43:44 26 4
gpt4 key购买 nike

我在 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<Book> 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 子集一起使用。如果该解决方案也可以执行反向序列化,那就太好了。

最佳答案

如果这不是 Silverlight,您可以使用 IDataContractSurrogate 使用 object[] (您的 JSON 中实际存在的内容)而不是 Book序列化/反序列化时。可悲的是, IDataContractSurrogate (以及使用它的 DataContractJsonSerializer 构造函数的重载)在 Silverlight 中不可用。

在 Silverlight 上,这里有一个 hacky 但简单的解决方法。导出Book来自实现 ICollection<object> 的类型的类.由于序列化 JSON 中的类型是 object[] ,框架会尽职尽责地将它序列化到你的 ICollection<object> 中。 ,这又可以用您的属性包装。

最简单(也是最骇人听闻的)就是从 List<object> 派生.这个简单的 hack 有一个缺点,即用户可以修改基础列表数据并弄乱您的属性。如果您是此代码的唯一用户,那可能没问题。通过更多的工作,您可以推出自己的 ICollection 实现。并且只允许足够的方法运行以使序列化工作,并为其余的抛出异常。我在下面包含了两种方法的代码示例。

如果上面的 hack 对你来说太难看,我相信有更优雅的方法来处理这个问题。您可能希望将注意力集中在创建自定义集合类型而不是 List<Book> 上为你的 collectionitems属性(property)。此类型可能包含类型为 List<object[]> 的字段(这是您的 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<Book> collectionitems { get; set; }
}

[CollectionDataContract]
class Book : List<object>
{
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);
}
}
}
}

更难、更简单的样本

这是第二个示例,显示了 ICollection 的手动实现,它阻止用户访问集合 -- 它支持调用 Add() 3 次(在反序列化期间)但不允许通过 ICollection<T> 进行修改. ICollection 方法是使用显式接口(interface)实现公开的,并且这些方法上有一些属性可以将它们从智能感知中隐藏起来,这应该会进一步减少 hack 因素。但是正如您所看到的,这是更多的代码。

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<Book> collectionitems { get; set; }
}

[CollectionDataContract]
class Book : ICollection<object>
{
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<object> System.Collections.Generic.IEnumerable<object>.GetEnumerator()
{
return new List<object> { 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<object>.Count
{
get { return 3; }
}

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

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

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

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

[EditorBrowsable(EditorBrowsableState.Never)]
bool System.Collections.Generic.ICollection<object>.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 .当你想在序列化/反序列化时用一种类型替换另一种类型时实现这个接口(interface)。在您的情况下,您要替换 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<Book> 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<Type> customDataTypes)
{
return; // not used
}
}


class Program
{
static void Main(string[] args)
{
DataContractJsonSerializer ser =
new DataContractJsonSerializer(
typeof(BookCollection),
new List<Type>(), /* 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);
}
}
}
}

关于c# - 使用 DataContractJsonSerializer 将数组值反序列化为 .NET 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2716718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com