C#如何对数组进行JSON分析?
在网上找了个实例,代码如下:
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Windows;
using System.Windows.Data;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Specialized;
namespace JsonArrayParsingTest
{
class Program
{
static void Main(string[] args)
{
var jsonString = @"[{""Id"": ""b3ec4e5c"",""AlbumName"": ""Dirty Deeds Done Dirt Cheap"",""Artist"": ""AC/DC"",
""YearReleased"": 1976,
""Entered"": ""2012-03-16T00:13:12.2810521-10:00"",
""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/61kTaH-uZBL._AA115_.jpg"",
""AmazonUrl"": ""http://www.amazon.com/gp/product/…ASIN=B00008BXJ4"",
""Songs"": [
{
""AlbumId"": ""b3ec4e5c"",
""SongName"": ""Dirty Deeds Done Dirt Cheap"",
""SongLength"": ""4:11""
},
{
""AlbumId"": ""b3ec4e5c"",
""SongName"": ""Love at First Feel"",
""SongLength"": ""3:10""
},
{
""AlbumId"": ""b3ec4e5c"",
""SongName"": ""Big Balls"",
""SongLength"": ""2:38""
}
]
},
{
""Id"": ""7b919432"",
""AlbumName"": ""End of the Silence"",
""Artist"": ""Henry Rollins Band"",
""YearReleased"": 1992,
""Entered"": ""2012-03-16T00:13:12.2800521-10:00"",
""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/51FO3rb1tuL._SL160_AA160_.jpg"",
""AmazonUrl"": ""http://www.amazon.com/End-Silence-Rollins-Band/dp/B0000040OX/ref=sr_1_5?ie=UTF8&qid=1302232195&sr=8-5"",
""Songs"": [
{
""AlbumId"": ""7b919432"",
""SongName"": ""Low Self Opinion"",
""SongLength"": ""5:24""
},
{
""AlbumId"": ""7b919432"",
""SongName"": ""Grip"",
""SongLength"": ""4:51""
}
]
}
]";
JArray jsonVal = JArray.Parse(jsonString) as JArray;
dynamic albums = jsonVal;
foreach (dynamic album in albums)
{
Console.WriteLine(album.AlbumName + " (" + album.YearReleased.ToString() + ")");
foreach (dynamic song in album.Songs)
{
Console.WriteLine("\t" + song.SongName);
}
}
Console.WriteLine(albums[0].AlbumName);
Console.WriteLine(albums[0].Songs[1].SongName);
}
}
}
可是会出现以下错误:
类型“System.Collections.Specialized.INotifyCollectionChanged”在未被引用的程序集中定义。必须添加对程序集“System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e”的引用。
该如何解决呢?
[解决办法]
http://json.codeplex.com/
Newtonsoft.Json.dll分为很多版本的,如果是已经编译好的dll,需要在对应的版本中使用,楼主应该是将Windows Phone版本的dll应用在了Console类的程序中,所以出错。
我个人用.net版本的dll编译以上的代码不会提示那个错误了。
在官方的安装包里,有Net20 Net30 Net40 WindowsPhone Protable等等好多版本的dll可以使用,也可以从源代码重新编译。