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.

2
  • 4
    Does this answer your question? How can I parse JSON with C#? Commented Feb 12, 2021 at 11:03
  • Create a class that matches your json and use JsonConvert.DeserializeObject Commented Feb 12, 2021 at 11:04

2 Answers 2

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; }
    }
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.