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

前端 未结 12 1066
旧巷少年郎
旧巷少年郎 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:04

    Deserializing using JsonConvert.DeserializeObject() function

    public class ApiValues
        {
            [JsonProperty("Address")]
            public string Address { get; set; }
    
            [JsonProperty("BaseUrl")]
            public string BaseUrl{ get; set; }
        }
    
    var json = 
    { 
        "Address":"some-address",
        "BaseUrl":"some-url-value"
    }
    
    
    var values = JsonConvert.DeserializeObject<ApiValues>(json);
    
    
    0 讨论(0)
  • 2020-11-22 10:05

    If, like me, you prefer to deal with strongly typed objects** go with:

    MyObj obj =  JsonConvert.DeserializeObject<MyObj>(jsonString);
    

    This way you get to use intellisense and compile time type error checking.

    You can easily create the required objects by copying your JSON into memory and pasting it as JSON objects (Visual Studio -> Edit -> Paste Special -> Paste JSON as Classes).

    See here if you don't have that option in Visual Studio.

    You will also need to make sure your JSON is valid. Add your own object at the start if it is just an array of objects. i.e. {"obj":[{},{},{}]}

    ** I know that dynamic makes things easier sometimes but I'm a bit ol'skool with this.

    0 讨论(0)
  • 2020-11-22 10:07

    You can use the C# dynamic type to make things easier. This technique also makes re-factoring simpler as it does not rely on magic-strings.

    JSON

    The JSON string below is a simple response from an HTTP API call, and it defines two properties: Id and Name.

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

    C#

    Use JsonConvert.DeserializeObject<dynamic>() to deserialize this string into a dynamic type then simply access its properties in the usual way.

    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, e.g. Id to an int and not a JValue (thanks to GFoley83 for the comment below).

    Note: The NuGet link for the Newtonsoft assembly is 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

    0 讨论(0)
  • 2020-11-22 10:08

    If you just need to get a few items from the JSON object, I would use Json.NET's LINQ to JSON JObject class. For example:

    JToken token = JObject.Parse(stringFullOfJson);
    
    int page = (int)token.SelectToken("page");
    int totalPages = (int)token.SelectToken("total_pages");
    

    I like this approach because you don't need to fully deserialize the JSON object. This comes in handy with APIs that can sometimes surprise you with missing object properties, like Twitter.

    Documentation: Serializing and Deserializing JSON with Json.NET and LINQ to JSON with Json.NET

    0 讨论(0)
  • 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<dynamic>)content).Where(p => p._id != null).Select(p=>p._id).ToList();
    
    List<string> codes = new List<string>();
    
    foreach (var code in contentCodes)
    {
        codes.Add(code?.ToString());
    }
    
    0 讨论(0)
  • 2020-11-22 10:09

    Finally Get State Name From JSON

    Thankyou!

    Imports System
    Imports System.Text
    Imports System.IO
    Imports System.Net
    Imports Newtonsoft.Json
    Imports Newtonsoft.Json.Linq
    Imports System.collections.generic
    
    Public Module Module1
        Public Sub Main()
    
             Dim url As String = "http://maps.google.com/maps/api/geocode/json&address=attur+salem&sensor=false"
                Dim request As WebRequest = WebRequest.Create(url)
            dim response As WebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
            dim reader As New StreamReader(response.GetResponseStream(), Encoding.UTF8)
              Dim dataString As String = reader.ReadToEnd()
    
            Dim getResponse As JObject = JObject.Parse(dataString)
    
            Dim dictObj As Dictionary(Of String, Object) = getResponse.ToObject(Of Dictionary(Of String, Object))()
            'Get State Name
            Console.WriteLine(CStr(dictObj("results")(0)("address_components")(2)("long_name")))
        End Sub
    End Module
    
    0 讨论(0)
提交回复
热议问题