Arane
Arane

Reputation: 323

How to extract data from this JSON format?

I have a JSON document and I'm trying to extract the individual data from this JSON doc. However, when I try to extract, all I get was some numbers that isn't inside the documents.

Here's the document:

user: [{
     serialNo: 1,
     details: [{ name: "John",
             job: "Receptionist" }]
 },
 {
     serialNo: 2,
     details: [{
             name: "Alan",
             job: "Salesman"
          }]
  }
]

So I tried doing this to extract the name "Alan"

using (var response = (HttpWebResponse)request.GetResponse())
{
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        var js = new JavaScriptSerializer();
        var objText = reader.ReadToEnd();
        var data = objText[1][0].name;
    }
}

All it returns me is some number that doesn't make sense, like '123' or '467' etc.

Upvotes: 0

Views: 168

Answers (1)

Dan Scott
Dan Scott

Reputation: 564

Have a look into Json.NET - Newtonsoft. it is a package that can be found with NuGet as well, just by typing in Newtonsoft :).

You can then make a model like so:

first solution:

using Newtonsoft.Json;
using System;

namespace UsersJSON
{

    public class UsersRepository
    {
        public User[] Users;
    }

    public class User
    {
        public int serialNo;
        public string[] details;
    }

    class Program
    {
        static void Main(string[] args)
        {
            var json = @"{
  users: [
  {
    serialNo: 1,
    details: ['John', 'Receptionist']
  },
  {
    serialNo: 2,
    details: ['Alan', 'Salesman']
  }]
}";
            var usersList = JsonConvert.DeserializeObject<UsersRepository>(json);
            Console.WriteLine(usersList.Users[0].details[0]); // prints "John"
            Console.ReadLine();
        }
    }
}

second solution:

using Newtonsoft.Json;
using System;

namespace UsersJSON
{

    public class UsersRepository
    {
        public User[] Users;
    }

    public class User
    {
        public int serialNo;
        public UserDetails details;
    }

    public class UserDetails
    {
        public string name;
        public string job;
    }

    class Program
    {
        static void Main(string[] args)
        {
            var json = @"{
  users: [
  {
    serialNo: 1,
    details: {name: 'John', job: 'Receptionist'}
  },
  {
    serialNo: 2,
    details: {name: 'Alan', job:'Salesman'}
  }]
}";
            var usersList = JsonConvert.DeserializeObject<UsersRepository>(json);
            Console.WriteLine(usersList.Users[0].details.name); // prints "John"
            Console.ReadLine();
        }
    }
}

Both require you to change your JSON output slightly.

Upvotes: 4

Related Questions