1

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?

2
  • is the structure of JSON will change every-time or be static ? Commented May 1, 2014 at 7:34
  • it actually depends on what parameter I use for the ETSY API :) Commented May 1, 2014 at 8:12

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much for this Sir, it really does work. I have one last question. What does (Of Integer) mean in result("user_id").Value(Of Integer)()? Let's say there are numerous array values under the results object and I'd like to search for a speficic user_id, do I have to loop through each array and use an IF statement or there's a search function provided by JSON.NET? Thank you very much :)
(Of Integer) basically tells Json.Net to cast the Value (the user_id in this case) to an Integer. Otherwise you would not be able to assign it to the Integer variable. To find a specific user_id you could either loop and use an if statement as you suggested, or you could use a LINQ query.
Okay Sir, that's good enough information. I will study LINQ. Your answer made my day :) Thank you.
1

Serialization and De-serialization of JSON object is better approach for using json string and JSON object. This Json converter is best suitable for such operation. Simply De-serialize the JSON object to C# or VB instance and you will get access to all properties.

1 Comment

Thank you for this. I appreciate it :) Would you mind putting a bit of sample code to explain what you said better? Or convert my code to get the same answer? Thank you.
0

There's no need to manipulate the JSON itself using string replace like you have done.

The cleanest way is to create a C# class with the same fields as the JSON you are parsing and deserializing to that as mentioned by Aaron. This makes the result a lot easier to use.

Alternatively you can leverage LINQ to JSON or dynamics to do something similar to your original answer without manipulating the JSON itself.

LINQ to JSON: http://james.newtonking.com/json/help/index.html?topic=html/LINQtoJSON.htm

Dynamics: http://james.newtonking.com/json/help/index.html?topic=html/QueryJsonDynamic.htm

1 Comment

Hi thank you for your answer :) My first solution was to create a class like your first option, but then Brian Rogers told me about JObject which is now supported in the latest version of JSON.NET. So I think I'm going with this option. I will check your links. Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.