【问题标题】:how can i get the data returned from my webservice into my classes using json如何使用 json 从我的 web 服务返回的数据到我的类中
【发布时间】:2014-02-04 16:26:36
【问题描述】:

基于http://json2csharp.com/,我有以下类:

public class Meta
{
    public string reason { get; set; }
    public bool success { get; set; }
}

public class Objects
{
    public int current_workspace { get; set; }
    public string first_name { get; set; }
    public bool is_staff { get; set; }
    public string key { get; set; }
    public string last_login { get; set; }
    public string last_name { get; set; }
    public string username { get; set; }
}

public class RootObject
{
    public Meta meta { get; set; }
    public Objects objects { get; set; }
}

如何使用以下方法获取类的各个字段中的数据:

public static void GetLoginDetails(string username, string password)
{
    // Customize URL according to geo location parameters
    var url = string.Format(loginUrl, username, password);

    // Syncronious Consumption
    var syncClient = new WebClient();
    var content = syncClient.DownloadString(url);

    if (!string.IsNullOrEmpty(content))
    {
        JsonConvert.DeserializeObject(content);
    }
}

我尝试了一些示例,但对象类字段为空 注意:通过调试,我可以看到 content 变量中的数据。

【问题讨论】:

    标签: c# json web-services json.net


    【解决方案1】:

    改变这个

    JsonConvert.DeserializeObject(content);
    

    到这里

    RootObject myRootObject = JsonConvert.DeserializeObject<RootObject>(content);
    

    那么您可以访问myRootObject 的任何属性(如果它不为空),即myRootObject.meta.reasonmyRootObject.objects.key 等。

    【讨论】:

    • myRootObject 为空,类的字段中没有数据
    • 您可以在您的问题中添加一些 json 示例数据吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    相关资源
    最近更新 更多