2013-06-03 55 views
0

JSON響應我使用小巧玲瓏返回一個IEnumerable<dynamic>物體的簽名:ASP.NET MVC格式從動態

date: 01/01/2011 
VarName = "VariableX" 
VariableValue = "Value 1" 

date: 01/01/2011 
VarName = "VariableY" 
VariableValue = "Value 2" 

我希望把它變成一個JSON響應:

{ date: 01/01/2011 
VariableX: Value 1 
VariableY: Value 2 
} 

..等,並會從任何一點開始!

感謝

編輯:

如果我變平作爲其返回我看對象:

[ 
{"date":"\/Date(1331683206000)\/","VariableName":"Variable1","VariableValue":"ValueX"}, 
{"date":"\/Date(1331683206000)\/","VariableName":"Variable2","VariableValue":"ValueY"}, 
{"date":"\/Date(1331683206000)\/","VariableName":"Variable3","VariableValue":"ValueZ"} 
] 

什麼,我基本上是在尋找指導是如何翻轉出來,所以它閱讀:

[ 
{"date":"\/Date(1331683206000)\/","Variable1","ValueX"}, 
{"date":"\/Date(1331683206000)\/","Variable2","ValueY"}, 
{"date":"\/Date(1331683206000)\/","Variable3","ValueZ"}, 
] 

編輯#2:固定所需輸出到:

[ 
    { 
     "date": "/Date(1331683206000)/", 
     "Variable1": "ValueX" 
    }, 
    { 
     "date": "/Date(1331683206000)/", 
     "Variable2": "ValueY" 
    }, 
    { 
     "date": "/Date(1331683206000)/", 
     "Variable3": "ValueZ" 
    } 
] 

編輯#3:

{ 
     "date": "/Date(1331683206000)/", 
     "Variable1": "ValueX", 
     "Variable2": "ValueY", 
     "Variable3": "ValueZ" 
    }, 
{ 
     "date": "/Date(1431683206000)/", 
     "Variable1": "ValueX", 
     "Variable2": "ValueY", 
     "Variable3": "ValueZ" 
    }, 
{ 
     "date": "/Date(151683206000)/", 
     "Variable1": "ValueX", 
     "Variable2": "ValueY", 
     "Variable3": "ValueZ" 
    } 
+0

你提的問題不夠清楚。目前缺少的是到目前爲止您嘗試過的代碼以及您遇到什麼困難。 –

+0

謝謝 - 我已經添加了更多信息 – chrr

+0

好吧,現在更清楚了。你試圖實現的是不可能的,因爲你顯示的是無效的JSON。 –

回答

3

什麼,我基本上是在尋找指導是如何翻轉出來,所以它讀取:

[ 
    {"date":"\/Date(1331683206000)\/","Variable1","ValueX"}, 
    {"date":"\/Date(1331683206000)\/","Variable2","ValueY"}, 
    {"date":"\/Date(1331683206000)\/","Variable3","ValueZ"} 
] 

恐怕這是不可能的,因爲你想要的輸出是無效的 JSON。

如果你的意思是這樣的:

[ 
    ["\/Date(1331683206000)\/","Variable1","ValueX"], 
    ["\/Date(1331683206000)\/","Variable2","ValueY"], 
    ["\/Date(1331683206000)\/","Variable3","ValueZ"] 
] 

那麼這是一個完全不同的問題。


UPDATE:

顯示您的實際需要的JSON後,你可以爲了實現IT項目的結果:

IEnumerable<dynamic> result = .... 
var viewModel = result.Select(x => 
{ 
    var result = new Dictionary<string, object>(); 
    result["date"] = x.date; 
    result[x.VariableName] = x.VariableValue; 
    return result; 
}).ToList(); 
return Json(viewModel, JsonRequestBehavior.AllowGet); 
+0

謝謝 - 向前思考,是否可以按日期對變量進行分組以使它們代表我的編輯#3? – chrr

+0

在更新#3中,您顯示了一個JavaScript對象,而不是數組。如果你在輸入中有兩個不同的日期怎麼辦?你想要的輸出是什麼? –

+0

如果有另一個日期期間,它會顯示另一個JSON組,因此在不同的日期對所有變量組合進行本質分組 - 我已更新我的編輯 – chrr