gpt4 book ai didi

c# - 如何在 C# 中反序列化 JSON 数组

转载 作者:太空宇宙 更新时间:2023-11-03 20:54:15 25 4
gpt4 key购买 nike

您好,我正在用 C# 开发 Web 应用程序。我有一个 JSON 对象。我正在尝试反序列化对象,如下所示。以下是我的结果。

 [ {
"id": "ce053195-ae48-4457-bb88-6ca32f236bd1",
"model": {
"objectId": [
"c760d95e-3fcb-43d1-a7db-111d3384ecbc"
],
"name": [
"Device1-Configuration"
]
},
"childs": 0,
"access": 0,
"allow": 0
},
{
"id": "42ad8eb6-9f35-447c-8ea0-e1346dee410c",
"model": {
"objectId": [
"c760d95e-3fcb-43d1-a7db-111d3384ecbc"
],
"name": [
"Device1-DeviceModel"
]
},
"childs": 1,
"access": 0,
"allow": 0
}
]

下面是我的模型。

public partial class Resource
{
public System.Guid Id { get; set; }

public Models Model { get; set; }

public bool Selected { get; set; }

public bool hasChildren { get; set; }

public bool IsAllowed { get; set; }
}

下面是我的模型类。

public partial class Models
{
public List<string> Name { get; set; }
}

我正在尝试从模型中分配名称数组。

foreach (JObject singScopeRes in result)
{
var permission = new Rbac.BusinessEntities.V2.Resource();
permission.Id = new Guid(singScopeRes["id"].ToString());
permission.Model = new Rbac.BusinessEntities.V2.Models()
{
Name= singScopeRes["model"]["name"][0]
};
}

这是抛出错误:

cannot implicit convert type newtonsoft.json.linq.jtoken to system.generic.list

有人可以帮我解决这个问题吗?

最佳答案

使用类似 json2csharp 的工具生成模型:

public class Model
{
public List<string> objectId { get; set; }
public List<string> name { get; set; }
}

public class Resource
{
public string id { get; set; }
public Model model { get; set; }
public int childs { get; set; }
public int access { get; set; }
public int allow { get; set; }
}

现在您可以像这样反序列化您的 json:

var obj = JsonConvert.DeserializeObject<Resource[]>(json);

如果您想坚持使用当前代码,您可以通过转换 JToken 并将其分配给 Name 属性来实现:

foreach (JObject singScopeRes in result)
{
var permission = new Rbac.BusinessEntities.V2.Resource();
permission.Id = new Guid(singScopeRes["id"].ToString());
permission.Model = new Rbac.BusinessEntities.V2.Models()
{
Name = (singScopeRes["model"]["name"]).ToObject<List<string>>()
};
}

关于c# - 如何在 C# 中反序列化 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52093621/

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