-5

I have a data string as

 [{"Name":"Jon","Age":"30"},{"Name":"Smith","Age":"25"}]

How to extract the data from it?

Please suggest me.

user1893874
  • 823
  • 4
  • 15
  • 38

2 Answers2

1

You need to deserialize the JSON into C# objects. Newtonsoft.Json is an excellent library for working with JSON.

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

string json = @"{"Name":"Jon","Age":"30"}";

Person x = JsonConvert.DeserializeObject<Person>(json);

string name = x.Name;
Luke Pothier
  • 1,030
  • 1
  • 7
  • 19
1

Using builtin .NET classes, you can use System.Web.Extensions

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Then in your code, you can deserialise the JSON i.e.

public void GetPersonFromJson(string json)
{
    //...
    json = " [{\"Name\":\"Jon\",\"Age\":\"30\"},{\"Name\":\"Smith\",\"Age\":\"25\"}]";

    JavaScriptSerializer oJS = new JavaScriptSerializer();
    Person[] person = oJS.Deserialize<Person[]>(json);
    //...
}

Or using NewtonSoft Nuget package:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Again in your code, you can deserialise using the NewtonSoft library i.e.

public void GetPersonFromJson(string json)
{
    //...
    json = " [{\"Name\":\"Jon\",\"Age\":\"30\"},{\"Name\":\"Smith\",\"Age\":\"25\"}]";
    var people = JsonConvert.DeserializeObject<List<Person>>(json);
    //...
}
MethodMan
  • 18,625
  • 6
  • 34
  • 52
Seany84
  • 5,526
  • 5
  • 42
  • 67