Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

前端 未结 12 1074
旧巷少年郎
旧巷少年郎 2020-11-22 10:04

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 som

12条回答
  •  感情败类
    2020-11-22 10:08

    Fairly late to this party, but I came across this issue myself today at work. Here is how I solved the issue.

    I was accessing a 3rd party API to retrieve a list of books. The object returned a massive JSON object containing roughly 20+ fields, of which I only needed the ID as a List string object. I used linq on the dynamic object to retrieve the specific field I needed and then inserted it into my List string object.

    dynamic content = JsonConvert.DeserializeObject(requestContent);
    var contentCodes = ((IEnumerable)content).Where(p => p._id != null).Select(p=>p._id).ToList();
    
    List codes = new List();
    
    foreach (var code in contentCodes)
    {
        codes.Add(code?.ToString());
    }
    

提交回复
热议问题