使用Newtonsoft将JSON反序列化为.NET对象(或者LINQ to JSON可能?)

段阳夏
2023-12-01

本文翻译自: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对象。

 类似资料: