使用JsonConvert.DeserializeObject反序列化嵌套的Json String

时间:2016-11-22 09:56:11

标签: c# xamarin xamarin.forms

嘿,我如何解析这个返回Json字符串。 enter image description here

仅获取我尝试此方法的数据

型号:

public class InstagramProfile
{
    public string username { get; set; }
    public string bio { get; set; }
    public string website { get; set; }
    public string profile_picture { get; set; }
    public string full_name { get; set; }
    public Counts counts { get; set; }
    public string id { get; set; }
 }

我的服务

 public class InstagramService
 {
    public async Task<InstagramProfile> GetInstagramProfile(string accessToken)
    {
        var httpClient = new HttpClient();
        var userJson = await httpClient.GetStringAsync(Constant.InstagramAu + accessToken);
        var instagramProfile = JsonConvert.DeserializeObject<InstagramProfile>(userJson);
        return instagramProfile;
    }
}

测试

    private async Task ExcLog()
    {
        var intg = new InstagramService();
        var token = "MyToken";
        var que = await intg.GetInstagramProfile(token);
        await DisplayAlert(PageKeys.Tags, que.full_name, "OK");
    }

如何获取数据?

4 个答案:

答案 0 :(得分:1)

尝试使用http://json2csharp.com/生成模型 之后,您可以将json反序列化为根对象。从那里你可以访问数据字段并进行处理。

答案 1 :(得分:1)

您需要一个包含整个JSON对象的模型..

public class InstagramMeta
{
    public int Code {get;set;}
}

public class InstagramResponse
{
    public InstagramMeta Meta {get;set;}
    public InstagramProfile Data {get;set;}
}

然后在InstagramResponse上反序列化。

如果您只想反序列化数据对象 - 请通过从模型中删除它来忽略Meta属性。

答案 2 :(得分:1)

要构建来自Michael Coxon的awnser,您还可以添加JsonProperty属性以将json名称映射到属性名称,然后您可以将其重命名为最适合您的命名约定:

public class InstagramProfile
{
    [JsonProperty("username")]
    public string Username { get; set; }
    [JsonProperty("bio")]
    public string Bio { get; set; }
    [JsonProperty("website")]
    public string Website { get; set; }
    [JsonProperty("profile_picture")]
    public string ProfilePicture { get; set; }
    [JsonProperty("full_name")]
    public string FullName { get; set; }
    ...
}

答案 3 :(得分:-1)

public class SerializedData
{
    public InstagramProfile data { get; set; }
}

反序列化为SerializedData。然后,您的数据将显示在.data