在 C# 中创建 Json 的问题 [关闭]
Posted
技术标签:
【中文标题】在 C# 中创建 Json 的问题 [关闭]【英文标题】:Issue creating Json in C# [closed] 【发布时间】:2022-01-05 02:17:53 【问题描述】:尝试在 C# 中创建一些 JSON 时遇到以下问题。
以下是我创建 JSON 的代码:
JObject data =
new JObject(
new JProperty("channel", "Test"),
new JProperty("terminal", "0"),
new JProperty("order",
new JArray(
new JObject(
new JProperty("orderId", txtSessionId.Text),
new JProperty("description", "test"),
new JProperty("currency", "EUR"),
new JProperty("totalAmount", txtPayAmount.Text),
new JProperty("customer",
new JArray(
new JObject(
new JProperty("name", "Test Name"),
new JProperty("phone", "00000000000"),
new JProperty("email", "test@test.com"))))))));
这会产生这个不正确的 JSON:
"channel": "Test",
"terminal": "0",
"order": [
"orderId": "30",
"description": "test",
"currency": "EUR",
"totalAmount": "10",
"customer": [
"name": "Test Name",
"phone": "00000000000",
"email": "test@test.com"
]
]
我希望它变成这样:
"channel":"Test",
"terminal":"0",
"order":[
"orderId":"30",
"description":"test",
"currency":"EUR",
"totalAmount":"10"
],
"customer":[
"name":"Test Name",
"phone":"00000000000",
"email":"test@test.com"
]
如果有人能指出正确的方向,那就太好了,谢谢。
【问题讨论】:
在您的new JProperty("customer"
之前添加))),
?
您是否缺少 order 数组的右括号? (就在打开 customer 数组之前?
【参考方案1】:
修正你的缩进会让你在哪里出错......
JObject data = new JObject(
new JProperty("channel", "Test"),
new JProperty("terminal", "0"),
new JProperty("order",
new JArray(
new JObject(
new JProperty("orderId", txtSessionId.Text),
new JProperty("description", "test"),
new JProperty("currency", "EUR"),
new JProperty("totalAmount", txtPayAmount.Text),
new JProperty("customer",
new JArray(
new JObject(
new JProperty("name", "Test Name"),
new JProperty("phone", "00000000000"),
new JProperty("email", "test@test.com")
)
)
)
)
)
)
);
如您所见,customer
对象位于order
数组中的第一个对象内。移动一些右括号应该可以解决它
JObject data = new JObject(
new JProperty("channel", "Test"),
new JProperty("terminal", "0"),
new JProperty("order",
new JArray(
new JObject(
new JProperty("orderId", txtSessionId.Text),
new JProperty("description", "test"),
new JProperty("currency", "EUR"),
new JProperty("totalAmount", txtPayAmount.Text),
)
)
),
new JProperty("customer",
new JArray(
new JObject(
new JProperty("name", "Test Name"),
new JProperty("phone", "00000000000"),
new JProperty("email", "test@test.com")
)
)
)
);
【讨论】:
以上是关于在 C# 中创建 Json 的问题 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章