Jared Mackey
Jared Mackey

Reputation: 4158

JSON Parsing C# model

I cannot seem to parse through some json to get it to a model.

The JSON:

{
    "status":"ok",
    "count":100,
    "data":[
        {"nickname":"God","id":null,"account_id":1000076613},
        {"nickname":"god0","id":null,"account_id":1005460397},
        {"nickname":"god1father","id":null,"account_id":1002495621},
        {"nickname":"God1Hand","id":null,"account_id":1003183995}]
}

My model:

public class UserModel
{
    public List<User> Users;
}

public class User
{

    public int AccountId { get; set; }

    public string Nickname { get; set; }

    public string Id { get; set; }

}

My Class:

var client = new HttpClient();
var task = await client.GetAsync(APIWebAddress);
var jsonstring = await task.Content.ReadAsStringAsync();
if (jsonstring == null) return null;
var serializer = new JavaScriptSerializer();
UserModel model = serializer.Deserialize<UserModel>(jsonstring);

The problem I am having is with the serializer. It does not return the model correctly causing me to get a null reference exception later when I try to look at the data. I have tried using the JavaScriptSerializer and the Json.Net deserializer.

Upvotes: 2

Views: 1006

Answers (2)

M Jun
M Jun

Reputation: 19

The problem in your code lies here:

UserModel model = serializer.Deserialize<UserModel>(jsonstring);

change it as below :

UserModel model = serializer.Deserialize<UserModel>(jsonstring.Result.ToString());

hope this helps you

Upvotes: 0

aloisdg
aloisdg

Reputation: 23521

Try with this

Model (generate with json2csharp)

public class User
{
    public string nickname { get; set; }
    public object id { get; set; }
    public int account_id { get; set; } // you cant change the name*
}

public class Users
{
    public string status { get; set; } // you cant skip this
    public int count { get; set; } // you cant skip this
    public List<User> data { get; set; }
}

Serializer

Here we are using Json.NET

Users users =  JsonConvert.DeserializeObject<Users>(json);

DEMO on DotnetFiddle

*You can rename it with an attribute

Upvotes: 5

Related Questions