我有一个具有这种结构的 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 爱好:钢琴