0

I have this sample code that i am working with. The json is a result of the http post.

var json = @"{'user': {
                        'country':'US',
                        'email':'[email protected]',
                        'first_name':'Test',
                        'last_name':'API',
                        'phone':null,
                        'zip':null,
                        'login_url':'https://new.site.com/xlogin/12325/abd9832cd92'
                        }
                    }";
        var jsonSerializer = new JavaScriptSerializer();
        var itemsList = (IDictionary<string, object>)jsonSerializer.DeserializeObject(json);
        var url = itemsList["user.login_url"];

On itemsList["user.login_url"] i am getting the following error:

 The given key was not present in the dictionary.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.

Source Error:


Line 545:        var jsonSerializer = new JavaScriptSerializer();
Line 546:        var itemsList = (IDictionary<string, object>)jsonSerializer.DeserializeObject(json);
Line 547:        var url = itemsList["user.login_url"];
Line 548:    }
Line 549:

Am i doing something wrong here? How should i access the first name, last name and url etc from this object? enter image description here

Alternately, how can i tie this result to a class that has following properties? I just need a pointer to a good resource.

public class User
{
    public string Country { get; set; }
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public string Zip { get; set; }
    public string LoginUrl { get; set; }
}

Thanks.

2
  • You hidden your URL in img but left that in code - 'login_url':'new.site.com/xlogin/12325/abd9832cd92' Commented Oct 31, 2014 at 14:25
  • 1
    The url in json is wrong, thats why i have left it there. Commented Oct 31, 2014 at 14:27

4 Answers 4

2

Well I really don't understand why u are using IDictionary to parse json object.

  1. Use Newtonsoft.Json instead of jsonSerializer much more essay to use.
  2. Go on http://json2csharp.com/ and generate your class to define you json (copy json and result is C# class).

Now tie your json to new RootObject not user:

using System;
using Newtonsoft.Json;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = @"{'user': {
                        'country':'US',
                        'email':'[email protected]',
                        'first_name':'Test',
                        'last_name':'API',
                        'phone':null,
                        'zip':null,
                        'login_url':'https://new.site.com/xlogin/12325/abd9832cd92'
                        }
                    }";

            RootObject userObj = JsonConvert.DeserializeObject<RootObject>(json.ToString());

        }
    }


    //generated with http://json2csharp.com/
    public class User
    {
        public string country { get; set; }
        public string email { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public object phone { get; set; }
        public object zip { get; set; }
        public string login_url { get; set; }
    }

    public class RootObject
    {
        public User user { get; set; }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, i'll take a look at it but at this time i have moved forward to second part of this project... which needs to be delivered soon.
1

"user.login_url" is the property path you'd expect to use in JavaScript ... try accessing the dictionary keys instead

var user = itemsList["user"] as IDictionary<string,object>;
var url = user["login_url"] as string;

3 Comments

This resulted in Cannot apply indexing with [] to an expression of type 'object'
Fixed the code - I didn't cast to the IDictionary from the user key
This worked for me. Since i am on a tight deadline due to the other end, i'll go with this and upvoted it as well. I'll mark this one as an answer. Later i'll take a look at json.net and will try to do it that way.
1

itemsList["user"] contains a second Dictionary. So you can navigate down to the login_url variable using

var user = (IDictionary<string, object>)itemsList["user"];
var login_url = user["login_url"];

Comments

0

Try using http://json.net/ it will give you a Dictionary with the types you want..

6 Comments

This does not answer the question.
@mason if he uses this library, he won't face this problem. The library itself puts the result in a Dictionary and he'll be able to access the values within a Dictionary (which is basically a better/ faster way to read/write JSON)
I am aware of what JSON.NET is and how it works. But if someone asks you how to build a house, you don't say "here's a hammer, it'll do what you want." Simply suggesting the tool isn't enough, you need to explain how to use the tool. Even if he switched to JSON.NET as you suggest, he'll likely use the incorrect syntax of itemsList["user.login_url"] unless you explain that's not correct.
@mason you're maybe right, but I was just helping him to get a better tool instead of the "var" and JavaScriptSerializer. He also stated in a comment above "Later i'll take a look at json.net and will try to do it that way."
I understand that. But the best way to do that is through a comment, not as an answer. Answers should be reserved for actually understanding the question. There's also nothing wrong with using var.
|

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.