我有一个类,在这个类中我遇到了一些从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创建一个容器..那么,当我使用反序列化程序时,为什么它不起作用呢?
发布于 2020-03-20 02:27:01
您需要使用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();
}
输出将为:
这是我的布局
发布于 2020-03-20 01:09:59
解释您的JSON与您发布的JSON类似,您应该更改您的Entity
类,并将UIL
的属性声明为string:
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
is a struct和我不知道你为什么要映射到这个结构。
端点可能正在工作,因为它没有像您所希望的那样映射该属性。
https://stackoverflow.com/questions/60761709
复制相似问题