反序列化JSON并分配给模型 [英] Deserialize JSON and assign to model
问题描述
作为我的Web API的一部分,我得到了以下JSON.
As part of my web api, I'm getting the following JSON returned.
["{\"InputType\":17,\"EngineSubType\":4,\"Filename\":\"targetFile.csv\",\"FileExtensionType\":\".csv\",\"IsLoadFile\":true,\"LoadContextId\":4121,\"ReportingDate\":\"2019-05-31T00:00:00\",\"IsSuccess\":false}"]
我想做的就是获取Filename
旁边的值,并将其分配给我的模型Filename
参数.
What I'm wanting to do is grab the value next to Filename
and assign it to my models Filename
parameter.
在我的项目中,我创建了一个单元测试来尝试获取该值,但是我所做的每一次尝试都失败了.
In my project I've created a unit test to experiment with grabbing that value, but each attempt I've making is failing.
在我的测试中,我具有以下DTO模型:
In my test I have following DTO Model:
public class HangfireTestDTO
{
public string InputType { get; set; }
public string Filename { get; set; }
}
然后我的文字逻辑是这样的:
Then my text logic is this:
[Fact]
public void TestDTO()
{
string data =
"[\"{\\\"InputType\\\":12,\\\"EngineSubType\\\":2,\\\"Filename\\\":\\\"targetFile.csv\\\",\\\"FileExtensionType\\\":\\\".csv\\\",\\\"IsLoadFile\\\":true,\\\"LoadContextId\\\":4120,\\\"ReportingDate\\\":\\\"2019-05-31T00:00:00\\\",\\\"IsSuccess\\\":false}\"]";
// fails here
var arguments = System.Text.Json.JsonSerializer.Deserialize<HangfireTestDTO>(data);
// This is wrong - ignore for now
Assert.Equal("targetFile.csv", arguments.ToString());
}
当我在测试中调试以上内容时,它会告诉我以下内容:
When I debug the above in my test it tells me the following:
JSON值无法转换为MyProject.HangfireTestDTO
The JSON value could not be converted to MyProject.HangfireTestDTO
然后我的想法使我通过将反序列化行修改为以下内容来再次尝试:
My thinking then led me to try again by modifying the deserialize line to the following:
var arguments = System.Text.Json.JsonSerializer.Deserialize<IEnumerable<HangfireTestDTO>>(data).FirstOrDefault();
但是用新行运行它时,出现以下错误:
But when running it with the new line, I get the following error:
JSON值无法转换为System.Collections.Generic.List
The JSON value could not be converted to System.Collections.Generic.List
我做错了什么?
推荐答案
第一个错误是由于InputType
引起的.应该是int
The first error is because of InputType
. It should be int
public class HangfireTestDTO
{
public int InputType { get; set; }
public string Filename { get; set; }
}
第二个错误是由于JSON
.在[
和{
之间有一个引号.我已经尝试了以下JSON
,并且有效.由于此报价,它变为List<string>
而不是List<HangfireTestDTO>
The second error is because of JSON
. There is an addition quotation between [
and {
. I have tried with below JSON
and it worked. Because of this quotation it becomes List<string>
and not List<HangfireTestDTO>
[
{
"InputType": 12,
"EngineSubType": 2,
"Filename": "targetFile.csv",
"FileExtensionType": ".csv",
"IsLoadFile": true,
"LoadContextId": 4120,
"ReportingDate": "2019-05-31T00:00:00",
"IsSuccess": false
}
]
然后查看JSON
应该是IEnumerable<HangfireTestDTO>
var arguments = JsonSerializer.Deserialize<IEnumerable<HangfireTestDTO>>(data);
这篇关于反序列化JSON并分配给模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!