2017-04-18 60 views
0

我的JSON对象中属性的名称需要通过字符串进行分配,我怎样才能用JObject来实现?或者我应该只是从字符串JObject.parse?我知道.Net Json文档,但是它非常基本,并且不会显示如下所示的任何示例。JSON指定带字符串变量的JObject属性名称

这是我现在有:

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 : '"[email protected]"', 
       buttons : [{ 
        type : '"[email protected]"', 
        "+Variable1+" : '"[email protected]"', 
        "+Variable2+" : '"[email protected]"' 
       }]  
     } 
    } 
}" 
+1

我不完全相信我跟随的问题。在第一个例子中,什么是用作属性名称的字符串? – dbc

+0

使用'Dictionary ' –

+0

@dbc因此,在第二个示例中,Variable1和Variable2可以很好地分配,因为它是一个简单的字符串。但是,在第一个示例中,我无法将属性名称variable1和variable2分配给实际变量,因此在运行代码时,名称为Variable1而不是其值。 – james

回答

1

可以使用从包含外匿名类型对象内部Creating JSON: Creating JSON with LINQ图案手动构造的内JObject,然后序列化整个匿名对象到JSON:

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))) 
     } 
    } 
}); 

样品fiddle

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 } 
       } 
      } 
     } 
    } 
}); 
+0

谢谢,但任何想法,我会这样比JArray和JObjects表现更好,就像在其他答案? – james

+0

@james:比起全新的一大堆'新JProperty'要少得多。 –

+0

顺便说一句,你的答案平均执行28毫秒,而另一方在我的Mac服务器上平均执行10毫秒。 :) – james