简体   繁体   中英

How to get attribute from a deserialized nested object?

I have a JSON file with this structure:

{
    "person1": [{"name": "Bobby"}, {"age": 25}, {"height": 178}, {"hobby": "piano"}],
    "person2": [{"name": "Tyler"}, { "age": 29}, {"height": 185}, {"hobby": "basketball"}],
    "person3": [{"name": "Mike"}, {"age": 30}, {"height": 192}, {"hobby": "football"}]
}

After that i want to get the attribute of every object in the data. So here is my code so far:

        JObject json = JObject.Parse(File.ReadAllText(*JSON file*));
        jsonString = json.ToString();       
        RootObject data = JsonConvert.DeserializeObject<RootObject>(jsonString);


        //Needed code here
        Console.Writeline(*hobby of Tyler*)

        Console.ReadKey();


    }
}
//====================================JSON class======================================
public class Person1
{
    public string name { get; set; }
    public Int16 age { get; set; }
    public Int16 height { get; set; }
    public string hobby { get; set; }
}

public class Person2
{
    public string name { get; set; }
    public Int16 age { get; set; }
    public Int16 height { get; set; }
    public string hobby { get; set; }
}

public class Person3
{
    public string name { get; set; }
    public Int16 age { get; set; }
    public Int16 height { get; set; }
    public string hobby { get; set; }
}

public class RootObject
{
    public List<Person1> person1 { get; set; }
    public List<Person2> person2 { get; set; }
    public List<Person3> person3 { get; set; }
}
}

I would be really appreciated if someone can help me with this. Moreover, to add all objects property to a list and tie them is essential as well. I'm stuck the moment.

Example: ListBox1: personID: person1, person2, person3 ListBox2: name/age/height/hobby TextBox3: output attribute

Thank you!

UPDATE: I have searching in darkness and until now this is what i get

class Program
    {
        public static string url = @"C:\Users\Admin\Desktop\getData3.json";
        public static string jsonString = "";
        static void Main(string[] args)
        {
            JObject json = JObject.Parse(File.ReadAllText(url));
            jsonString = json.ToString();

            //==========Second Method=======================================
            Console.WriteLine("==============================================================");
            Console.Write("name: "+ person.person1[0].name);
            Console.Write("   age: "+ person.person1[1].age);
            Console.Write("   height: "+ person.person1[2].height);
            Console.WriteLine("   hobby: "+ person.person1[3].hobby);


            Console.ReadKey();

        }
    }
   //CLass===================================
    public class Person
    {

        public string name { set; get; }

        public int age { set; get; }

        public int height { set; get; }


        public string hobby { set; get; }
    }

    public class RootObject
    {
        public List<Person> person1 { get; set; }
        public List<Person> person2 { get; set; }
        public List<Person> person3 { get; set; }

    }
}

OUTPUT console: Name: Bobby age: 25 height: 178 hobby: piano

Well to start with it seems like you don't completely understand classes and objects. You don't want to create a new class for each person but a new instance of the person class. For example:

Person person1 = new Person();
Person person2 = new Person();
Person person3 = new Person();

This code creates 3 instances of the person class. You are now free to set/get the properties of each instance of the person class.

Note: that the above code uses the default constructor, you could create your own constructor to assign the value of the persons properties at the time of instantiation.

Your person class could look like this:

public class Person {
   public string Name { get; set; }
   public Int16 Age { get; set; }
   public Int16 Height { get; set; }
   public string Hobby { get; set; }

    public override string ToString()
    {
        return $"Name: {Name}, Age: {Age}, Height: {Height}, Hobby: {Hobby}";
    }
}

Note: that is convention to use PascalCase for properties as they are accessor methods, it's also good etiquette and often helpful to override ToString()

Okay, so now we can look at your JSON. You are creating three JSON Arrays, which I don't think you want, so I've changed it to three JSON Objects:

{
  "person1": {"name": "Bobby", "age": 25, "height": 178, "hobby": "piano"},

  "person2": {"name": "Tyler", "age": 29, "height": 185, "hobby": "basketball"},

  "person3": {"name": "Mike", "age": 30, "height": 192, "hobby": "football"}
}

Now we have cleaned up your JSON we can tie it together:

static void Main(string[] args) {   
  //Create an instance of the person class
  Person person1 = new Person(); 

  //Create a json object from your file 
  JObject json = JObject.Parse(File.ReadAllText(@"json-file-path"));

  //Assign the instances properties using the json object 
  person1.Name = json["person1"]["name"].ToString();
  person1.Age =  Convert.ToInt16(json["person1"]["age"]);
  person1.Height = Convert.ToInt16(json["person1"]["height"]);
  person1.Hobby = json["person1"]["hobby"].ToString();

  //Write the person object to the console
  Console.WriteLine(person1.ToString());
}

When getting values from a JObject first you must get the key, in this case the key is "person1", and then get value assigned to a token by using the tokens name, then you must appropriately handle the value returned by the token, this can take many forms but above this achieved through simple Converts and ToStrings.

Now you can rinse and repeat creating an instance of the person class, assigning its properties from your already created JObject instance and using them however you'd like, in my case writing it to the console.

EDIT TO USE ORIGINAL JSON STRUCTURE

static void Main(string[] args)
 {   
  //Create an instance of the person class
  Person person1 = new Person();
  Person person2 = new Person();
  Person person3 = new Person();

  //Create a json object from your file 
   JObject json = JObject.Parse(File.ReadAllText(@"json-file-path"));

  //Get the jarray for each person 
  JArray a1 = (JArray)json["person1"];
  JArray a2 = (JArray)json["person2"];
  JArray a3 = (JArray)json["person3"];

  //person 1
  person1.Name = a1[0]["name"].ToString();
  person1.Age =  Convert.ToInt16(a1[1]["age"]);
  person1.Height = Convert.ToInt16(a1[2]["height"]);
  person1.Hobby = a1[3]["hobby"].ToString();

  //person 2
  person2.Name = a2[0]["name"].ToString();
  person2.Age = Convert.ToInt16(a2[1]["age"]);
  person2.Height = Convert.ToInt16(a2[2]["height"]);
  person2.Hobby = a2[3]["hobby"].ToString();

   //person 3
   person3.Name = a3[0]["name"].ToString();
   person3.Age = Convert.ToInt16(a3[1]["age"]);
   person3.Height = Convert.ToInt16(a3[2]["height"]);
   person3.Hobby = a3[3]["hobby"].ToString();

    Console.WriteLine(person1.ToString());
    Console.WriteLine(person2.ToString());
    Console.WriteLine(person3.ToString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM