Pagorn
Pagorn

Reputation: 612

How to access data json.net array in c#

I can't access all of json data that it is deserialized by json.net. How can I access it. It's null when I WriteLine in console.

Account.cs

public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}

main class

 string json2 = @"{'Accounts' :[{
 'Email': '[email protected]',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin']
},
{
 'Email': '[email protected]',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'Userz',
    'Adminz'
  ]
}]}";

    List<Account> account = new List<Account>();
    account.Add(JsonConvert.DeserializeObject<Account>(json2));


    // [email protected]
    Console.Write(account[0].Email);

Upvotes: 2

Views: 252

Answers (2)

Borislav Borisov
Borislav Borisov

Reputation: 408

The JSON string you have can not be parsed the way you want. Try this instead:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        string json2 = @"[{
     'Email': '[email protected]',
      'Active': true,
      'CreatedDate': '2013-01-20T00:00:00Z',
      'Roles': [
        'User',
        'Admin']
    },
    {
     'Email': '[email protected]',
      'Active': true,
      'CreatedDate': '2013-01-20T00:00:00Z',
      'Roles': [
        'Userz',
        'Adminz'
      ]
    }]";

    List<Account> account = new List<Account>();
    account.AddRange(JsonConvert.DeserializeObject<List<Account>>(json2));


    // [email protected]
    Console.Write(account[0].Email);
    }
}

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}

Edit: or actually the answer @dotnetom provided solves your problem in case you don't have control over the json format

Upvotes: 1

dotnetom
dotnetom

Reputation: 24901

The reason is that you are missing one more class here:

public class Root
{
    public List<Account> Accounts { get; set; }
}

You need this class, because your JSON has a property which is called Accounts, so you need to have it as well in your C# code in order to deserialize successfully.

And then you deserialise this object use such code:

var root = JsonConvert.DeserializeObject<Root>(json2);

// you can access first element by using
Console.Write(root.Accounts[0].Email);    //prints [email protected]

Upvotes: 1

Related Questions