2017-04-18 61 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