使用Newtonsoft將JSON反序列化爲.NET對象(或者LINQ to JSON可能?)

本文翻譯自:Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

I know there are a few posts about Newtonsoft so hopefully this isn't exactly a repeat...I'm trying to convert JSON data returned by Kazaa's API into a nice object of some kind 我知道有一些關於Newtonsoft的帖子,所以希望這不是一個重複...我試圖將Kazaa的API返回的JSON數據轉換成某種形狀的好對象

WebClient client = new WebClient();
Stream stream = client.OpenRead("http://api.kazaa.com/api/v1/search.json?q=muse&type=Album");
StreamReader reader = new StreamReader(stream);

List<string> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(reader.Read().ToString());

foreach (string item in list)
{
    Console.WriteLine(item);
}

//Console.WriteLine(reader.ReadLine());
stream.Close();

That JsonConvert line is just the most recent one I was trying...I'm not quite getting it and was hoping to eliminate some footwork by asking you guys. 那個JsonConvert系列只是我最近嘗試過的一個......我不太瞭解它並且希望通過問你們來消除一些步法。 I was originally trying to convert it into a Dictionary or something...and actually, I just need to snag a couple of values in there so judging by the documentation, maybe Newtonsoft's LINQ to JSON might be a better choice? 我原本試圖將它轉換成字典或其他東西......實際上,我只需要在那裏獲取一些值,因此根據文檔來判斷,也許Newtonsoft的LINQ to JSON可能是更好的選擇? Thoughts/Links? 思考/鏈接?

Here is an example of the JSON return data: 以下是JSON返回數據的示例:

{
  "page": 1,
  "total_pages": 8,
  "total_entries": 74,
  "q": "muse",
  "albums": [
    {
      "name": "Muse",
      "permalink": "Muse",
      "cover_image_url": "http://image.kazaa.com/images/69/01672812 1569/Yaron_Herman_Trio/Muse/Yaron_Herman_Trio-Muse_1.jpg",
      "id": 93098,
      "artist_name": "Yaron Herman Trio"
    },
    {
      "name": "Muse",
      "permalink": "Muse",
      "cover_image_url": "htt p://image.kazaa.com/images/54/888880301154/Candy_Lo/Muse/Candy_Lo-Muse_1.jpg",
      "i d": 102702,
      "artist_name": "\u76e7\u5de7\u97f3"
    },
    {
      "name": "Absolution",
      "permalink": " Absolution",
      "cover_image_url": "http://image.kazaa.com/images/65/093624873365/Mus e/Absolution/Muse-Absolution_1.jpg",
      "id": 48896,
      "artist_name": "Muse"
    },
    {
      "name": "Ab solution",
      "permalink": "Absolution-2",
      "cover_image_url": "http://image.kazaa.com/i mages/20/825646911820/Muse/Absolution/Muse-Absolution_1.jpg",
      "id": 118573,
      "artist _name": "Muse"
    },
    {
      "name": "Black Holes And Revelations",
      "permalink": "Black-Holes-An d-Revelations",
      "cover_image_url": "http://image.kazaa.com/images/66/093624428466/ Muse/Black_Holes_And_Revelations/Muse-Black_Holes_And_Revelations_1.jpg",
      "id": 48813,
      "artist_name": "Muse"
    },
    {
      "name": "Black Holes And Revelations",
      "permalink": "Bla ck-Holes-And-Revelations-2",
      "cover_image_url": "http://image.kazaa.com/images/86/ 825646911486/Muse/Black_Holes_And_Revelations/Muse-Black_Holes_And_Revelations_1 .jpg",
      "id": 118543,
      "artist_name": "Muse"
    },
    {
      "name": "Origin Of Symmetry",
      "permalink": "Origin-Of-Symmetry",
      "cover_image_url": "http://image.kazaa.com/images/29/825646 912629/Muse/Origin_Of_Symmetry/Muse-Origin_Of_Symmetry_1.jpg",
      "id": 120491,
      "artis t_name": "Muse"
    },
    {
      "name": "Showbiz",
      "permalink": "Showbiz",
      "cover_image_url": "http: //image.kazaa.com/images/68/825646182268/Muse/Showbiz/Muse-Showbiz_1.jpg",
      "id": 60444,
      "artist_name": "Muse"
    },
    {
      "name": "Showbiz",
      "permalink": "Showbiz-2",
      "cover_imag e_url": "http://image.kazaa.com/images/50/825646912650/Muse/Showbiz/Muse-Showbiz_ 1.jpg",
      "id": 118545,
      "artist_name": "Muse"
    },
    {
      "name": "The Resistance",
      "permalink": "T he-Resistance",
      "cover_image_url": "http://image.kazaa.com/images/36/825646864836/ Muse/The_Resistance/Muse-The_Resistance_1.jpg",
      "id": 121171,
      "artist_name": "Muse"
    }
  ],
  "per_page": 10
}

I did some more reading and found Newtonsoft's LINQ to JSON is exactly what I wanted...using WebClient, Stream, StreamReader, and Newtonsoft...I can hit Kazaa for JSON data, extract a URL, download the file, and do it all in like seven lines of code! 我做了一些閱讀,發現Newtonsoft的LINQ to JSON正是我想要的......使用WebClient,Stream,StreamReader和Newtonsoft ......我可以點擊Kazaa獲取JSON數據,提取URL,下載文件,然後進行操作全部像七行代碼! I love it. 我喜歡它。

WebClient client = new WebClient();
Stream stream = client.OpenRead("http://api.kazaa.com/api/v1/search.json?q=muse&type=Album");
StreamReader reader = new StreamReader(stream);

Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());

// Instead of WriteLine, 2 or 3 lines of code here using WebClient to download the file
Console.WriteLine((string)jObject["albums"][0]["cover_image_url"]);
stream.Close();

This post gets so many hits I thought it might be helpful to include the "using" bits that are discussed in the comments. 這篇文章獲得瞭如此多的點擊量,我認爲包含評論中討論的“使用”位可能會有所幫助。

using(var client = new WebClient())
using(var stream = client.OpenRead("http://api.kazaa.com/api/v1/search.json?q=muse&type=Album"))
using (var reader = new StreamReader(stream))
{
    var jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());
    Console.WriteLine((string) jObject["albums"][0]["cover_image_url"]);
}

#1樓

參考:https://stackoom.com/question/Jvb5/使用Newtonsoft將JSON反序列化爲-NET對象-或者LINQ-to-JSON可能


#2樓

You can use the C# dynamic type to make things easier. 您可以使用C# dynamic類型來簡化操作。 This technique also makes re-factoring simpler as it does not rely on magic-strings. 這種技術也使得重新分解更簡單,因爲它不依賴於魔術字符串。

JSON JSON

The JSON string below is a simple response from an HTTP API call, and it defines two properties: Id and Name . 下面的JSON字符串是來自HTTP API調用的簡單響應,它定義了兩個屬性: IdName

{"Id": 1, "Name": "biofractal"}

C# C#

Use JsonConvert.DeserializeObject<dynamic>() to deserialize this string into a dynamic type then simply access its properties in the usual way. 使用JsonConvert.DeserializeObject<dynamic>()將此字符串反序列化爲動態類型,然後以通常的方式訪問其屬性。

dynamic results = JsonConvert.DeserializeObject<dynamic>(json);
var id = results.Id;
var name= results.Name;

If you specify the type of the results variable as dynamic , instead of using the var keyword, then the property values will correctly deserialize, eg Id to an int and not a JValue (thanks to GFoley83 for the comment below). 如果將results變量的類型指定爲dynamic ,而不是使用var關鍵字,則屬性值將正確反序列化,例如Idint而不是JValue (感謝GFoley83以獲取下面的註釋)。

Note : The NuGet link for the Newtonsoft assembly is http://nuget.org/packages/newtonsoft.json . 注意 :Newtonsoft程序集的NuGet鏈接是http://nuget.org/packages/newtonsoft.json

Package : You can also add the package with nuget live installer, with your project opened just do browse package and then just install it install, unistall, update , it will just be added to your project under Dependencies/NuGet :您也可以使用nuget實時安裝程序添加包,打開項目只需瀏覽包然後安裝它, 安裝,unistall,更新 ,它只會被添加到您的項目下Dependencies / NuGet


#3樓

With the dynamic keyword, it becomes really easy to parse any object of this kind: 使用dynamic關鍵字,解析此類對象變得非常容易:

dynamic x = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
var page = x.page;
var total_pages = x.total_pages
var albums = x.albums;
foreach(var album in albums)
{
    var albumName = album.name;

    // Access album data;
}

#4樓

Also, if you're just looking for a specific value nested within the JSON content you can do something like so: 此外,如果您只是在尋找嵌套在JSON內容中的特定值,您可以執行以下操作:

yourJObject.GetValue("jsonObjectName").Value<string>("jsonPropertyName");

And so on from there. 等等。

This could help if you don't want to bear the cost of converting the entire JSON into a C# object. 如果您不想承擔將整個JSON轉換爲C#對象的成本,這可能會有所幫助。


#5樓

Deserialize and get the value (when the collection is dynamic): 反序列化並獲取值(當集合是動態的時):

// First serializing
dynamic collection = new { stud = stud_datatable }; // The stud_datable is the list or data table
string jsonString = JsonConvert.SerializeObject(collection);


// Second Deserializing
dynamic StudList = JsonConvert.DeserializeObject(jsonString);

var stud = StudList.stud;
foreach (var detail in stud)
{
    var Address = detail["stud_address"]; // Access Address data;
}

#6樓

I like this method: 我喜歡這種方法:

using Newtonsoft.Json.Linq;
// jsonString is your JSON-formatted string
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<string, object> dictObj = jsonObj.ToObject<Dictionary<string, object>>();

You can now access anything you want using the dictObj as a dictionary. 您現在可以使用dictObj作爲字典訪問任何您想要的dictObj You can also use Dictionary<string, string> if you prefer to get the values as strings. 如果您希望將值作爲字符串獲取Dictionary<string, string>也可以使用Dictionary<string, string>

You can use this same method to cast as any kind of .NET object. 您可以使用相同的方法來轉換爲任何類型的.NET對象。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章