使用设置的值将JSON转换为C#内联类 [英] Convert JSON to C# inline class with values set
问题描述
我需要从设置了值的JSON对象生成测试用例(使用IEnumerable<TestCaseData>
).我找不到任何在线工具来生成具有设置值的C#类(大量的生成类).在测试用例中反序列化Json会使测试无效(一个只能测试代码),所以我做了这个正则表达式.
I need to generate test cases (using IEnumerable<TestCaseData>
) from JSON objects that have values set. I couldn't find any tools online that would generate C# classes that have values set (Plenty that generate classes). Deserializing Json in test cases would invalidate test (One should only be testing the code), so I did this regex.
这不是完美的方法,但是当所有属性均为相同类型(小数或布尔)时,它可以与大多数基本格式正确的JSON配合使用,
模式:"([a-zA-Z]?[a-zA-Z0-9].*)" ?: ?((true|false|null)|([\d].*))
,替换$1 = $2M
,但是当有很多类型并且它们混合在一起时,我会被拧紧.
It's not perfect but worked just fine with most basic well formatted JSON when all properties are of same type (decimals or bools),
pattern: "([a-zA-Z]?[a-zA-Z0-9].*)" ?: ?((true|false|null)|([\d].*))
, replace $1 = $2M
however when there are many types and they are mixed I get screwed.
我确定有人在我之前遇到了这个问题,并且我正在重新发明车轮,所以简而言之.
I am sure someone ran into this before me and I am reinventing wheel so in a nutshell.
我如何做到这一点:
{
"LegalFeeNet": 363.54,
"LegalFeeVat": 72.708,
"DiscountNet": 0.0,
"DiscountVat": 0.0,
"OtherNet": 12.0,
"OtherVat": 2.4,
"DisbursementNet": 220.0,
"DisbursementVat": 0.0,
"AmlCheck": null,
"LegalSubTotal": 363.54,
"TotalFee": 450.648,
"Discounts": 0.0,
"Vat": 75.108,
"DiscountedPrice": 360.5184,
"RecommendedRetailPrice": 450.648,
"SubTotal": 375.54,
"Name": "Will",
"IsDiscounted": false,
"CustomerCount": 3
}
成为这个:
ClassName {
LegalFeeNet = 363.54M,
LegalFeeVat = 72.708M,
DiscountNet = 0.0M,
DiscountVat = 0.0M,
OtherNet = 12.0M,
OtherVat = 2.4M,
DisbursementNet = 220.0M,
DisbursementVat = 0.0M,
AmlCheck = nullM,
LegalSubTotal = 363.54M,
TotalFee = 450.648M,
Discounts = 0.0M,
Vat = 75.108M,
DiscountedPrice = 360.5184M,
RecommendedRetailPrice = 450.648M,
SubTotal = 375.54M,
Name = "Will",
IsDiscounted = false,
CustomerCount = 3
}
哪种最快/最方便的解决方案是生成具有从JSON对象设置的属性的C#类?
推荐答案
我也在这里寻找相同问题的解决方案.
I was also here in search of a solution to the same problem.
被接受的答案缺少了我想要的某些功能,因此最终创建了此功能 https://jsontocsharpconverter.web.app/
The accepted answer missed some features I wanted, so ended up creating this https://jsontocsharpconverter.web.app/
希望..它可以帮助某人.
Hopefully.. it helps someone.
这篇关于使用设置的值将JSON转换为C#内联类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!