【发布时间】:2020-01-24 20:29:01
【问题描述】:
我正在使用JsonForm 在我的 MVC 核心 Web 应用程序中生成动态表单。我在视图模型的以下代码中使用System.Text.Json.JsonSerializer.Serialize 来生成一个简单的单字段表单。我的目标是最终将此 json 存储在数据库中并从那里检索它。
public TestsViewModel GetFormControls1()
{
var myJsonModel = new
{
schema = new
{
client = new
{
type = "object",
title = "Client",
properties = new
{
forename = new
{
type = "string",
title = "Forename",
minLength = 3,
maxLength = 10,
}
}
}
},
form = new List<Object>
{
new {
key = "client.forename",
title = "Forename"
}
},
value = new
{
client = new
{
forename = "",
}
}
};
TestsViewModel homeVm = new TestsViewModel();
homeVm.FormControls = System.Text.Json.JsonSerializer.Serialize(myJsonModel);
return homeVm;
}
上面的代码运行良好,并生成以下 json 模式,然后用于创建表单。
{
"schema": {
"client": {
"type": "object",
"title": "Client",
"properties": {
"forename": {
"type": "string",
"title": "Forename",
"minLength": 3,
"maxLength": 10
}
}
}
},
"form": [
{
"key": "client.forename",
"title": "Forename"
}
],
"value": {
"client": {
"forename": ""
}
}
}
我现在需要为我的 json 生成一个枚举,以便选择性别的下拉菜单可以出现在表单中。但是,我无法通过 c# 代码做到这一点。有人可以帮忙吗?我希望我的 c# 代码生成以下 json(请注意模式和表单中的两个性别条目)。
{
"schema": {
"client": {
"type": "object",
"title": "Client",
"properties": {
"forename": {
"type": "string",
"title": "Forename",
"minLength": 3,
"maxLength": 10
},
"gender": {
"type": "string",
"title": "Gender",
"enum": [
"male",
"female",
"alien"
]
}
}
}
},
"form": [
{
"key": "client.forename",
"title": "Forename"
},
{
"key": "client.gender",
"titleMap": {
"male": "Dude",
"female": "Dudette",
"alien": "I'm from outer space!"
}
}
],
"value": {
"client": {
"forename": ""
}
}
}
我尝试使用以下代码,但 enum 是 c# 中的关键字,所以我收到错误。
gender = new
{
type = "string",
title = "Gender",
enum = "[male, female, alien]"
}
同样Enum = "[male, female, alien]" 产生"Enum": "[male, female, alien]" 而不是"enum": [ "male", "female", "alien" ]
我有一个性别查找表,我最终将使用它以某种方式生成上述枚举,因此任何关于此的想法都会有所帮助。
更新 @dbc 的评论为我的大部分问题提供了解决方案。但是,如果我尝试将字符串映射到 int,我仍然在努力生成 titleMap json。
var gender3 = new
{
type = "string",
title = "Gender",
titleMap = new List<string> { new string("1" + ":" + "Male"), new string("2" + ":" + "Female")}
};
以上代码产生
{
"type": "string",
"title": "Gender",
"titleMap": [
"1:Male",
"2:Female"
]
}
但是,我需要 1 和 Male 在自己的双引号内 { } 而不是 [ ] ,如下所示。
{
"type": "string",
"title": "Gender",
"titleMap": {
"1": "Male",
"2": "Female"
}
}
【问题讨论】:
-
您的问题很长,但是您只是在寻找
@enum = new [] { "male", "female", "alien" },吗?见dotnetfiddle.net/dwZFsW。请参阅:How do I use a C# keyword as a property name? 和 All possible array initialization syntaxes,了解字符串数组的数组初始值设定项语法。 -
@dbc 这解决了我的大部分查询。有关剩余问题,请参阅上面的更新部分。还将您的评论添加到答案部分,以便我接受。
标签: c# json asp.net-core system.text.json