gpt4 book ai didi

c# - 将 Json 字符串转换为对象列表

转载 作者:太空狗 更新时间:2023-10-29 23:39:48 26 4
gpt4 key购买 nike

我从外部 webapi 获取一个带有 json 对象的字符串。我有一个将对象放入 ExpandoObject 列表的代码,但必须有另一个不使用动态对象的解决方案。

代码如下:

System.Net.HttpWebRequest request = 

(System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://example.com/api/users.json");
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Headers["Authorization"] = "API key="+somekey;
// Ignore Certificate validation failures (aka untrusted certificate + certificate chains)
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
//response from the api
string responseFromServer = reader.ReadToEnd();
//serialize the data
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
System.Collections.IList users = (System.Collections.IList)((IDictionary<string, object>)((IDictionary<string, object>)jss.DeserializeObject(responseFromServer))["data"])["users"];

List<System.Dynamic.ExpandoObject> api_users = new List<System.Dynamic.ExpandoObject>();
//putting the expandable objects in list
foreach (var u in users)
{
var user = ((Dictionary<string, object>)((IDictionary<string, object>)u)["User"]);
dynamic data = new System.Dynamic.ExpandoObject();
//putting the user attributes into dynamic object
foreach (var prop in user)
{
((IDictionary<String, Object>)data).Add(prop.Key, prop.Value);
}
api_users.Add(data);
}

这是 json 字符串的示例:

"data": {
"users": [
{
"User": {
"user_id": "6741",
"email": "mail@mail.com",
"first_name": "Mark",
"last_name": "Plas",
"street_address": "",
"post_code": "",
"city": ""
},
"CreatedBy": {
"id": null,
"name": null
},
"ModifiedBy": {
"id": null,
"name": null
}
},...(can have more users here)

最佳答案

您可以使用众多 C# JSON 解析器之一来执行此操作。我个人比较喜欢JSON.Net (您可以通过 NuGet 安装)。它可以反序列化为动态对象以及您自己的静态类型类。

关于c# - 将 Json 字符串转换为对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15799597/

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