Search code examples
.netjsonwinformsparsingjson.net

JSON.NET Dynamic Parsing (more efficient solution)


I'm using JSON.NET to parse JSON data. I have got dynamic parsing using JObject class to work but I'm looking for a more efficient way. This is just the basics and my final solution will be much more complicated, but first thing's first, I need to get the basics.

So I have this JSON data...

{
    "count":1,
    "results": [{
        "user_id":5029420,
        "login_name":"EtsyStore",
        "creation_tsz":1282269739,
        "referred_by_user_id":null,
        "feedback_info": {
            "count":3038,
            "score":100
         }
     }],
     "params": {
         "user_id":"etsystore"
     },
     "type":"User",
    "pagination":{}
}

Here's my current code so far... I'd like to get the value of user_id under the results object.

Dim p1 = JObject.Parse(json)
Dim p2 = JObject.Parse(p1("results").ToString.Replace("[", "").Replace("]", ""))
MsgBox(p2("user_id"))

So I'm able to get the value of user_id but I don't think this is the most efficient way of doing it. Is there another way of doing it?


Solution

  • When using a JSON parser, you should not need to directly manipulate the JSON string (that is the job of the parser), nor parse the JSON more than once (the data is already in memory from the first parse). So you are right, what you are doing is not the best way to extract the data.

    Here is an example of how you can extract the user_id and other result data from the JSON using the LINQ-to-JSON API (i.e. JObjects / JTokens). Because results is an array in the JSON, I'm assuming there might not always be just one result, so I will use a loop here.

    ' load all the JSON data into a JObject
    Dim p1 As JObject = JObject.Parse(json)
    
    ' loop over the "results" array to get each child object (result)
    For Each result As JToken In p1("results").Children()
    
        ' extract the data from each result
        Dim userId As Integer = result("user_id").Value(Of Integer)()
        Dim loginName As String = result("login_name").ToString()
        Dim creationTsz As Long = result("creation_tsz").Value(Of Long)()
    
        ' the feedback info is one level further down
        Dim feedback As JToken = result("feedback_info")
        Dim feedbackCount As Integer = feedback("count").Value(Of Integer)()
        Dim feedbackScore As Integer = feedback("score").Value(Of Integer)()
    
        ' do something with the data; perhaps write it to the console
        Console.WriteLine("User ID: " + userId.ToString())
        Console.WriteLine("Login Name: " + loginName.ToString())
        Console.WriteLine("Creation TSZ: " + creationTsz.ToString())
        Console.WriteLine("Feedback Count: " + feedbackCount.ToString())
        Console.WriteLine("Feedback Score: " + feedbackScore.ToString())
        Console.WriteLine()
    
    Next