[英]How can I easily create readable JSON objects in C# .Net Core similar to JavaScript
In JavaScript I can easily create an object and assign variables with some very basic notation such as:在 JavaScript 中,我可以轻松地创建一个对象并使用一些非常基本的符号分配变量,例如:
const Object = JSON.parse('
{
"something": outsideVariable,
"someArray": [
"hey",
"there"
]
}
');
Is there a simple way to do this with C# that is clean and easy to assign variables too?是否有一种简单的方法可以使用 C# 来做到这一点,既干净又易于分配变量? I experimented a bit with the JsonObject but the code for that looks needlessly messy, for example:我对 JsonObject 进行了一些试验,但它的代码看起来不必要的混乱,例如:
JsonObject jsonPayload = new JsonObject
{
["documentId"] = documentID,
["testMode"] = true,
["signers"] = new JsonArray
{
new JsonObject
{
["label"] = "John Smith",
["contactMethod"] = new JsonArray
{
new JsonObject
{
["type"] = "link"
}
}
}
}
};
I also tried using the literal symbol (@) with a string, but it ends up injecting carriage returns and linefeeds, and inserting variables winds of being a great deal of concatination.我还尝试将文字符号 (@) 与字符串一起使用,但它最终会注入回车符和换行符,并且插入变量会导致大量的串联。
IMHO , the most close you want is this恕我直言,你想要的最接近的是这个
var jsonPayload = new
{
documentId = 1,
testMode = true,
signers = new object[]
{
new {
label="John Smith",
contactMethod= new object[]
{
new {
type="link"
}
}
}
}
};
and code和代码
var json= System.Text.Json.JsonSerializer
.Serialize(jsonPayload,new JsonSerializerOptions { WriteIndented = true });
//or if you need
var jsonParsed= JsonDocument.Parse(json);
result结果
{
"documentId": 1,
"testMode": true,
"signers": [
{
"label": "John Smith",
"contactMethod": [
{
"type": "link"
}
]
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.