[英]How to deserialize a json file with multidimensional array to convert it to object in c#
I have the following Json file 我有以下Json文件
[
{
"photos": [
{
"photo": "http://example.com/media/origin/11820846/photo_80_4_.jpg",
"photo_order": 1,
"caption": "photo_80_4_"
}
],
"id": "11820846"
}
],
[
{
"photos": [
{
"photo": "http://example.com/media/new_images/
bookingpal/united%20arab%20emirates/
12564676/product65093-015.jpg",
"photo_order": 1,
"caption": ""
}
],
"id": "12564676"
}
]
The original file is longer but basically it repeats. 原始文件较长,但基本上会重复。
With the following code I can see the data for the first array but it fails when it gets to the second array. 通过以下代码,我可以看到第一个数组的数据,但是当它到达第二个数组时会失败。
Why? 为什么?
class Program {
static void Main(string[] args) {
using (var st = new StreamReader(@"C:\Users\mc\Desktop\photojson.txt")) {
string Json = st.ReadToEnd();
List<TVID> IdList = JsonConvert.DeserializeObject<List<TVID>>(Json);
foreach (var ids in IdList) {
Console.WriteLine(ids.ID);
foreach (var myphoto in ids.photos) {
Console.WriteLine(myphoto.Photo + "," + myphoto.Photo_order + "," +
myphoto.Caption);
Console.Read();
}
}
}
}
public class TVPhotos {
public string Photo { get; set; }
public string Photo_order { get; set; }
public string Caption { get; set; }
}
public class TVID {
public string ID { get; set; }
public List<TVPhotos> photos { get; set; }
}
}
To fix the error you mentioned in the comments ("Additional text encountered after finished reading JSON content") you need to surround the JSON with square brackets as below: 要解决您在注释中提到的错误(“读取JSON内容后遇到其他文本”),您需要将JSON括在方括号中,如下所示:
[
[
{
"photos": [
{
"photo": "http://example.com/media/origin/11820846/photo_80_4_.jpg",
"photo_order": 1,
"caption": "photo_80_4_"
}
],
"id": "11820846"
}
],
[
{
"photos": [
{
"photo": "http://example.com/media/new_images/bookingpal/united%20arab%20emirates/12564676/product65093-015.jpg",
"photo_order": 1,
"caption": ""
}
],
"id": "12564676"
}
]
]
And to deserialize this you can use List< List< TVID > > such as: 要反序列化,可以使用List <List <TVID>>,例如:
using (var st = new StreamReader(@"sample1.json"))
{
string Json = st.ReadToEnd();
List<List<TVID>> IdListList = JsonConvert.DeserializeObject<List<List<TVID>>>(Json);
foreach (var IdList in IdListList)
{
foreach (var ids in IdList)
{
Console.WriteLine(ids.ID);
foreach (var myphoto in ids.photos)
{
Console.WriteLine(myphoto.Photo + "," + myphoto.Photo_order + "," +
myphoto.Caption);
Console.Read();
}
}
}
}
Looking at the JSON I think a single array would do the same job but if you can't change the JSON the above changes should make it work. 查看JSON,我认为单个数组可以完成相同的工作,但是如果您不能更改JSON,则上述更改应该可以使其工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.