在 C# 中使用 DataContractJsonSerializer 反序列化 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17409655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deserialization of JSON object by using DataContractJsonSerializer in C#
提问by stvn03
I'm sure this question has been asked over and over again, but for some reason, I still can't manage to get this to work.
我确定这个问题已经被反复问过,但由于某种原因,我仍然无法让它发挥作用。
I want to deserialize a JSON object that contains a single member; a string array:
我想反序列化一个包含单个成员的 JSON 对象;一个字符串数组:
[{"idTercero":"cod_Tercero"}]
This is the class that I'm trying to deserialize into:
这是我试图反序列化的类:
[DataContract]
public class rptaOk
{
[DataMember]
public string idTercero { get; set; }
public rptaOk() { }
public rptaOk(string idTercero)
{
this.idTercero = idTercero;
}
}
This is the method that I try to deserialize:
这是我尝试反序列化的方法:
public T Deserialise<T>(string json)
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
T result = (T)deserializer.ReadObject(stream);
return result;
}
}
And so I try to fill the object:
所以我尝试填充对象:
rptaOk deserializedRpta = deserializarOk(rpta);
But for some reason, this returns ""
但由于某种原因,这将返回“”
MessageBox.Show(deserializedRpta.idTercero);
回答by evanmcdonnal
I think you're making this a lot more difficult than it needs to be. Firstly, your sample json and the class you're trying to deserialize into do not have an array of strings. They have a single property of type string. Secondly, why are you using this class DataContractJsonSerializer? You're not doing anything with it that you can't get from a simple call to json.NET's generic deserialization method. I would remove all of your code except the class definition and replace it with this simple one liner;
我认为你让这件事变得比需要的要困难得多。首先,您的示例 json 和您尝试反序列化的类没有字符串数组。它们有一个字符串类型的属性。其次,你为什么要使用这个类DataContractJsonSerializer?你没有做任何你无法从简单调用 json.NET 的通用反序列化方法中得到的东西。我会删除除类定义之外的所有代码,并用这个简单的单行代码替换它;
rptaOk[] myInstances = JsonConvert.DeserializeObject<rptaOk>(jsonString);
Also, no matter what the structure of your json is, if you have a class to correctly model it that method will correctly deserialize it. If you want to enforce some kind of contract I recommend using json schemas which json.NET also supports. If you use a schema it enforces a rigid contract, if you attempt to deserialize into an object there is something of an implicit contract. I don't know every scenario which will cause it to throw, but if your json is too far from the class definition it will. If your class has properties that don't appear in the json I believe they will just get initialized with the default values for that type.
此外,无论您的 json 的结构是什么,如果您有一个正确建模的类,该方法将正确地反序列化它。如果您想强制执行某种合同,我建议使用 json.NET 也支持的 json 模式。如果您使用模式,它会强制执行严格的契约,如果您尝试反序列化为对象,则存在某种隐式契约。我不知道会导致它抛出的每个场景,但如果你的 json 离类定义太远,它会。如果您的类具有未出现在 json 中的属性,我相信它们只会使用该类型的默认值进行初始化。
EDIT: I just noticed your json is actually an array of objects. So you simply need to make the lhs of that assignment an array or rptaOkobjects, rather than a singleton.
编辑:我刚刚注意到你的 json 实际上是一个对象数组。因此,您只需将该赋值的 lhs 设为数组或rptaOk对象,而不是单例。
回答by Victor Franchi
I don't know if your're wiling to change the library that you're using, but I use library "Newtonsoft.Json" to desserialize JSON objects, it's pretty easy to use
我不知道您是否愿意更改您正在使用的库,但我使用库“Newtonsoft.Json”来反序列化 JSON 对象,它非常易于使用
[HttpPost]
public void AddSell(string sellList)
{
var sellList = JsonConvert.DeserializeObject<List<Sell>>(sellListJson);
BD.SaveSellList(sellList);
}
As you can see you can deserialize a whole json object list to a List<> fo the type "Sell", an object that i've created... And, of course, you can do that to an array too. I don't know the correct syntax for this, but you can convert this list to an array afterwards
如您所见,您可以将整个 json 对象列表反序列化为“Sell”类型的 List<>,这是我创建的一个对象……当然,您也可以对数组执行此操作。我不知道正确的语法,但您可以稍后将此列表转换为数组
Hope this helps
希望这可以帮助
回答by Perpetualcoder
Without any dependencies outside of the .net framework, you could do it this way
在 .net 框架之外没有任何依赖,你可以这样做
[DataContract(Name="rptaOk")]
public class RptaOk
{
[DataMember(Name="idTercero")]
public string IdTercero { get; set; }
}
[CollectionDataContract(Name="rptaOkList")]
public class RptaOkList : List<RptaOk>{}
var stream = new StreamReader(yourJsonObjectInStreamFormat);
var serializer = new DataContractSerializer(typeof(RptaOkList));
var result = (RptOkList) serializer.ReadObject(stream);

