how*_*doI 5 c# json asp.net-core json-serialization
我有一个类,其中我在从 json 文件填充 jsonElement 时遇到一些问题
{
"entities": [
{
"name": "DateTimeENT1",
"description": "This a example",
"uil": {
"uill": "This is my Layout"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
正在被反序列化到此类中:
public class Container {
public ICollection<Entity> Entities {get; set;}
}
public class Entity {
public string Name {get; set;}
public string Descripton {get; set;}
UIL Uil {get; set;}
}
public class UIL{
JsonElement Uill {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
这就是我反序列化它的方式:
var input= JsonConvert.DeserializeObject<Container>(File.ReadAllText(@"init.json"));
Run Code Online (Sandbox Code Playgroud)
当我运行这个时,我收到一条错误消息'Error converting value "This is my Layout" to type 'System.Text.Json.JsonElement'. 我该如何克服这个问题?
所有这一切的奇怪部分是我可以在我的控制器端点上使用相同的输入
public IActionResult Put([FromBody] Container container)
Run Code Online (Sandbox Code Playgroud)
没有任何问题,它会使用给定的 json 创建一个容器。那么为什么当我使用反序列化器执行此操作时它不起作用?
Sel*_*diz 10
您需要使用JsonDocument.Parse而不是JsonConverter.DeserializeObject.
static void Main(string[] args)
{
var jsonInput= @"{
""entities"":
[
{
""name"": ""DateTimeENT1"",
""description"": ""This a example"",
""uil"": {
""uill"": ""This is my Layout""
}
}
]
}";
using (JsonDocument doc = JsonDocument.Parse(jsonInput))
{
JsonElement root = doc.RootElement;
JsonElement entities = root.GetProperty("entities");
//Assuming you have only 1 item, if you have more you can use EnumerateArray and MoveNext()..
JsonElement uilItem = entities[0].GetProperty("uil");
JsonElement uillItem = uilItem.GetProperty("uill");
Console.WriteLine(uillItem.GetString());
}
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
输出将是:
这是我的布局
解释您的 JSON 与您发布的 JSON 类似,您应该更改您的Entity类并将 的 属性声明为UIL字符串:
public class Container {
public ICollection<Entity> Entities {get; set;}
}
public class Entity {
public string Name {get; set;}
public string Descripton {get; set;}
UIL Uil {get; set;}
}
public class UIL {
public string Uill {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
JsonElement 是一个结构体,我不知道为什么你可能想映射到这个结构体。
端点可能正在工作,因为它没有按照您想要的方式映射该属性。
| 归档时间: |
|
| 查看次数: |
12998 次 |
| 最近记录: |