[英]Error converting string to type 'System.Text.Json.JsonElement
我有一個類,其中我在從 json 文件填充 jsonElement 時遇到了一些問題
{
"entities": [
{
"name": "DateTimeENT1",
"description": "This a example",
"uil": {
"uill": "This is my Layout"
}
}
]
}
正在反序列化為此類:
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;}
}
這就是我反序列化它的方式:
var input= JsonConvert.DeserializeObject<Container>(File.ReadAllText(@"init.json"));
當我運行它時,我收到一條錯誤消息,指出'Error converting value "This is my Layout" to type 'System.Text.Json.JsonElement'.
我該如何克服?
關於這一切的奇怪部分是我可以在我的控制器端點上使用相同的輸入
public IActionResult Put([FromBody] Container container)
它可以毫無問題地使用給定的 json 創建一個容器。
您需要使用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();
}
輸出將是:
這是我的布局
解釋您的 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;}
}
JsonElement
是一個結構體,我不知道你為什么要映射到這個結構體。
端點可能正在工作,因為它沒有按照您的需要映射該屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.