在C#中使用DataContractJsonSerializer与子场JSON对象的反序列化的字符串 [英] Deserialization of JSON object with sub field as string using DataContractJsonSerializer in C#
问题描述
下面是我的JSON:
{
"Name": "Eli",
"Age": 4,
"Children": {
"Moshe": {
"Age": 6,
"Characteristics": "Nice;Good;"
},
"Yossi": {
"Age": 3,
"Characteristics": "Hero;Brave"
}
}
}
下面是我的JSON反序列化功能:
Here is my JSON deserialization function:
public static object FromJSON<T>(string json)
{
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return serializer.ReadObject(stream);
}
}
我想它序列化到人
目标:
[DataContract]
public class Person
{
[DataMember]
public int Age;
[DataMember]
public string Name;
[DataMember]
public string Children;
}
正如你所看到的,我的不希望要获得孩子
进入字典,而是把它作为是 - JSON字符串
As you can see, I do not want to get Children
into dictionary but to get it as is - JSON string.
目前我做的像这样的:
Person p = (Person)Extensions.FromJSON<Person>(output);
和我得到的异常说:
有一个错误反序列化类型JSONSerialization.Person的对象。结束元素的命名空间'项目'项目'的预期。找到的元素:从命名空间'项目''一个项目
There was an error deserializing the object of type JSONSerialization.Person. End element 'item' from namespace 'item' expected. Found element 'a:item' from namespace 'item'.
只是为了澄清:我不知道希望孩子子场被解析。
Just to clarify: I do not want the children sub field to be parsed.
推荐答案
如果您使用的JavaScriptSerializer那么你将能够序列化儿童钥匙插入如果需要一个充满活力的领域和阅读它以JSON格式。
If you use the JavaScriptSerializer then you will be able to serialize the Children key into a dynamic field and read it in JSON format if required.
在人
对象尝试使用动态
类型,而不是字符串
为孩子
属性。
In the Person
object try and use the dynamic
type instead of string
for the Children
property.
public static T FromJavaScriptSerializer<T>(string json)
{
var serializer = new JavaScriptSerializer();
return serializer.Deserialize<T>(json);
}
public static string ToStringOutput(object dynamicField)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(dynamicField);
}
您可以使用方法如下:
var person = FromJavaScriptSerializer<Person>(output);
Console.WriteLine(ToStringOutput(person.Children));
以下将出现在控制台
{摩西:{时代:6,特色:好,好,},贝纳:{时代:3,特色:英雄,勇敢 }}
{"Moshe":{"Age":6,"Characteristics":"Nice;Good;"},"Yossi":{"Age":3,"Characteristics":"Hero;Brave"}}
这篇关于在C#中使用DataContractJsonSerializer与子场JSON对象的反序列化的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!