将字符串转换为JSON C#

学习...

我有正在使用的示例代码。json是http发布的结果。

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"];

itemsList["user.login_url"]我收到以下错误:

 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:

我在这里做错什么了吗?我应该如何从该对象访问名字,姓氏和url等?在此处输入图片说明

或者,我如何将此结果绑定到具有以下属性的类?我只需要一个指向好的资源的指针。

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; }
}

谢谢。

斯图

“ user.login_url”是您希望在JavaScript中使用的属性路径...尝试访问字典键

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章