0

I'm trying to get JSON content with Newtonsoft.Json. To read one variable i have that method and It's working fine:

        dynamic data = JObject.Parse(json);
        return data.FirstName;

The problem begins if I want to read variable which is in array ex:

{"family": [{"fatherFirstName": "John", "motherFirstName": "July"}, {"fatherFirstName": "Jack", "motherFirstName": "Monika"]}

And for example I only want to get every father's first name. Anybody know how can I do this?

Edit1: Ok I fixed the convert from JArray to string but now there is problem that It reads family variable properly but If I want to get exact variable from Array it says that variable like this doesn't exist.

mmmx19
  • 21
  • 5
  • 4
    Does this answer your question? [How can I parse JSON with C#?](https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c) – kapsiR Feb 12 '21 at 11:03
  • Create a class that matches your json and use `JsonConvert.DeserializeObject` – Magnetron Feb 12 '21 at 11:04

2 Answers2

2
public class familyData
{
  public string fatherFirstName {get; set;}
  public string motherFirstName {get; set;}      
}
public class familyList
{
  public List<familyData> family
}            

and in your method

var data = JsonConvert.DeserializeObject<familyList>(json);

2

First of all, your JSON string has an invalid format. You can check it here to validate. Secondly, the best way to do this is to create a class and than use JsonConvert.DeserializeObject. On your case, here is the full working solution:

    static void Main(string[] args)
    {
        string json = @"{'family': [{'fatherFirstName': 'John', 'motherFirstName': 'July'}, {'fatherFirstName': 'Jack', 'motherFirstName': 'Monika'}]}";
        Families families = JsonConvert.DeserializeObject<Families>(json);
        foreach (var family in families.family)
            Console.WriteLine(family.fatherFirstName);
    }

    public class Families
    {
        public List<Family> family { get; set; }
    }

    public class Family
    {
        public string fatherFirstName { get; set; }
        public string motherFirstName { get; set; }
    }
Adnand
  • 562
  • 1
  • 8
  • 25