我的JSON对象中的属性名称需要通过字符串分配,如何使用JObject执行此操作?或者我应该从字符串中只是JObject.parse?我知道.Net Json文档,但它非常基础,并没有显示如下的任何示例。
以下是我现在所拥有的:
return JObject.FromObject(new {
attachment = new {
type = "template",
payload = new {
template_type = "button",
text = Title,
buttons = new {
type = type,
Variable1 = Value,
Variable2 = Payload
}
}
}
});
另外,如果我按照下面的方式执行string.parse方式,这是格式化字符串的最佳方法吗?
JObject.Parse(@"{
attachment : {
type : 'template',
payload : {
template_type : 'button',
text : '"+Title+@"',
buttons : [{
type : '"+Type+@"',
"+Variable1+" : '"+Value+@"',
"+Variable2+" : '"+Payload+@"'
}]
}
}
}"
答案 0 :(得分:1)
您可以使用外部匿名类型对象中包含的Creating JSON: Creating JSON with LINQ模式手动构造内部var obj = JObject.FromObject(new
{
attachment = new
{
type = "template",
payload = new
{
template_type = "button",
text = Title,
buttons = new JArray( new JObject(
new JProperty("type", Type),
new JProperty(Variable1, Value),
new JProperty(Variable2, Payload)))
}
}
});
,然后将整个匿名对象序列化为JSON:
Business = {
1: { Country: "France" },
2: { Country: "France" },
3: { Country: "UnitedKingdom" },
4: { Country: "France" }
}
示例fiddle。
答案 1 :(得分:1)
Dictionary<string,object>
使用buttons
,例如:
var obj = JObject.FromObject(new
{
attachment = new
{
type = "template",
payload = new
{
template_type = "button",
text = Title,
buttons = new object[]
{
new Dictionary<string,object>()
{
{ "type", "type" },
{ Variable1, Value },
{ Variable2, Payload }
}
}
}
}
});