gpt4 book ai didi

c# - 从 JSON 字符串中获取 C#-Object-Array

转载 作者:太空狗 更新时间:2023-10-29 21:22:07 25 4
gpt4 key购买 nike

所以,这是我的课:

public class User
{
public User() { }

public string Username { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

}

这就是我的 JSON 字符串的样子:

{"results":[{"FirstName":"firstname1","LastName":"lastname1","Password":"TestPassword","Username":"TestUser","createdAt":"2015-03-02T17:36:25.232Z","objectId":"a8bKXDg2Y2","updatedAt":"2015-03-02T20:35:48.755Z"},{"FirstName":"firstname2","LastName":"lastname2","Password":"TestPw","Username":"TestUser2","createdAt":"2015-03-02T20:35:26.604Z","objectId":"2XPIklE3uW","updatedAt":"2015-03-02T20:35:53.712Z"}]}

我想从中获取一个 User[] 用户。我的问题是 {"results:":[....]}-Part.

我试过这种方法:

JavaScriptSerializer js = new JavaScriptSerializer();
User[] user = js.Deserialize<User[]>(jsonString);

但我认为结果部分以某种方式搞砸了一切。解决此问题的最佳方法是什么?

最佳答案

尝试定义一个将反射(reflect)您的 JSON 结构的包装模型:

public class MyModel
{
public User[] Results { get; set; }
}

现在您可以继续将您的 JSON 字符串反序列化回这个包装模型:

JavaScriptSerializer js = new JavaScriptSerializer();
MyModel model = js.Deserialize<MyModel>(jsonString);

现在没有什么可以阻止您取回用户集合了:

User[] user = model.Results;

关于c# - 从 JSON 字符串中获取 C#-Object-Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28819040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com