0

我有一个具有这种结构的 JSON 文件:

{
    "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"}]
}

之后我想获取数据中每个对象的属性。所以这是我到目前为止的代码:

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

如果有人可以帮助我,我将不胜感激。此外,将所有对象属性添加到列表并绑定它们也是必不可少的。我被卡住了。

示例: ListBox1:personID:person1、person2、person3 ListBox2:姓名/年龄/身高/爱好 TextBox3:输出属性

谢谢!

更新:我在黑暗中搜索,直到现在这就是我得到的

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

    }
}

输出控制台: 姓名:鲍比 年龄:25 身高:178 爱好:钢琴

4

1 回答 1

1

首先,您似乎并不完全了解类和对象。您不想为每个人创建一个新类,而是为该人类创建一个新实例。例如:

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

这段代码创建了 person 类的 3 个实例。您现在可以自由设置/获取 person 类的每个实例的属性。

注意:以上代码使用默认构造函数,您可以创建自己的构造函数来在实例化时分配persons属性的值。

您的人员类可能如下所示:

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}";
    }
}

注意:这是对属性使用 PascalCase 的约定,因为它们是访问器方法,这也是一种很好的礼仪,并且通常有助于覆盖 ToString()

好的,现在我们可以查看您的 JSON。您正在创建三个 JSON 数组,我认为您不需要,因此我将其更改为三个 JSON 对象:

{
  "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"}
}

现在我们已经清理了您的 JSON,我们可以将其绑定在一起:

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

从 JObject 获取值首先必须获取键,在这种情况下键是“person1”,然后通过使用令牌名称获取分配给令牌的值,然后您必须适当处理令牌返回的值,这可以采用多种形式,但通过简单的 Converts 和 ToStrings 实现。

现在,您可以冲洗并重复创建 person 类的实例,从您已经创建的 JObject 实例中分配其属性并根据需要使用它们,在我的情况下将其写入控制台。

编辑使用原始 JSON 结构

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());
}
于 2017-04-08T04:07:19.533 回答