Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize array of json objects with json object inside

How can I deserialize array of json objects in c#? Here's my json:

[{"id":"255521115", "user":"username","userinfo":{"id":"158","online":"false"}}]

I have this code to get username:

 [JsonProperty("user")]
 public string Username { get; set; }

How can I get values of the userinfo? I want online value that is inside userinfo object.

like image 964
Matthew Avatar asked Nov 28 '25 01:11

Matthew


1 Answers

There is one cool feature in VS2013. If you copy your JSON to clipboard and in Visual Studio click EDIT -> Paste Special -> Paste JSON as Classes it will generate class structure for you. All you need is to rename some properties if you want to. In your case modified version of classes will be:

public class Obj
{
    public string Id { get; set; }

    [JsonProperty("User")]
    public string UserName { get; set; }

    public Userinfo Userinfo { get; set; }
}

public class Userinfo
{
    public string Id { get; set; }
    public string Online { get; set; }
}

And then you can easily deserialize your JSON string:

var json = @"[{""id"":""255521115"", ""user"":""username"",""userinfo"":{""id"":""158"",""online"":""false""}}]";
var objs = JsonConvert.DeserializeObject<IList<Obj>>(json);
like image 134
Aleksandr Ivanov Avatar answered Nov 30 '25 14:11

Aleksandr Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!