问题描述
我使用的是Json.NET库。什么是串行/通过C#反序列化数组的JSON的最便捷的方式是什么?例如,我在尝试反序列化与下列文本(读取文件):
I'm using a Json.NET library. What's the most convenient way of serializing/deserializing arrays in JSON via C#? For example, I'm trying to deserialize the following text (reading from file):
{
"Name": "Christina",
"Gender": "female",
"Favorite_numbers": [11, 25 ,23]
}
我在读上面的文字从文件到一个变量:
I'm reading the text above from file to a variable:
JObject o = JObject.Parse(File.ReadAllText("input.txt"))
然后,当我试图提取数组 [11,24,23]
与
int[] num = (int[]) o["Favorite_numbers"]
我收到一个错误。
I receive an error.
我是什么做错了吗?我该如何正确地读出数组?我该如何正确地阅读下列类型的2调光阵列 [1,2,3],[4,5,6]]
?
What am I doing wrong? How do I correctly read an array? How do I correctly read a 2-dim arrays of the following kind [[1, 2, 3], [4, 5, 6]]
?
推荐答案
在 Favorite_numbers
属性将是类型 JArray
因为没有办法为它推断出什么类型应该。反序列化对象的最方便的方法将是定义一个C#类,并使用 JsonConvert.DeserializeObject< T>(...)
办法(S)反序列化JSON你定义的类。
The Favorite_numbers
property is going to be of type JArray
since there is no way for it to infer what type it should be. The most convenient way of deserializing that object is going to be to define a C# class for it and use the JsonConvert.DeserializeObject<T>(...)
method(s) to deserialize the JSON to your defined class.
这篇关于Json.NET:串行化/反序列化阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!