我使用Rob Conery的Massive框架从数据库中选择IEnumerable<dynamic>
。结构以平面格式Poco C#返回。我需要转换数据并将其输出到Json数组(格式显示在底部)。
我以为我可以使用linq进行转换(我的不成功的努力如下所示):
using System.Collections.Generic;
using System.Json;
using System.Linq;
using System.ServiceModel.Web;
....
IEnumerable<dynamic> list = _repository.All("", "", 0).ToList();
JsonArray returnValue = from item in list
select new JsonObject()
{
Name = item.Test,
Data = new dyamic(){...}...
};
这是我想要生成的Json:
[
{
"id": "1",
"title": "Data Title",
"data": [
{
"column1 name": "the value",
"column2 name": "the value",
"column3 name": "",
"column4 name": "the value"
}
]
},
{
"id": "2",
"title": "Data Title",
"data": [
{
"column1 name": "the value",
"column2 name": "the value",
"column3 name": "the value",
"column4 name": "the value"
}
]
}
]
答案 0 :(得分:3)
以下是使用Json.Net
的示例List<int> list = new List<int>() {1 , 2};
string json = JsonConvert.SerializeObject(
list.Select(x => new{
id = x.ToString(),
title = "title " + x.ToString(),
data = Enumerable.Range(3,2).Select(i=> new {column1=i,column2=i*i})
})
, Newtonsoft.Json.Formatting.Indented
);
输出:
[
{
"id": "1",
"title": "title 1",
"data": [
{
"column1": 3,
"column2": 9
},
{
"column1": 4,
"column2": 16
}
]
},
{
"id": "2",
"title": "title 2",
"data": [
{
"column1": 3,
"column2": 9
},
{
"column1": 4,
"column2": 16
}
]
}
]
答案 1 :(得分:0)
好的,这就是我最终看到的所有看起来很笨拙的海鲂:
[WebGet(UriTemplate = "/tools/data/get?tool={tool}&filters={filters}")]
public JsonArray GetData(string tool, string[,] filters)
{
IEnumerable<dynamic> list = _repository.All("", "", 0).ToList();
IEnumerable<JsonObject> jsonList = from item in list
select new JsonObject()
{
new KeyValuePair<string, JsonValue>("Id", item.Id),
new KeyValuePair<string, JsonValue>("Name", item.Title),
new KeyValuePair<string, JsonValue>("Data", new JsonObject()
{
new KeyValuePair<string, JsonValue>("Product", item.Product),
new KeyValuePair<string, JsonValue>("Suite", item.Suite),
new KeyValuePair<string, JsonValue>("Package", item.Package),
new KeyValuePair<string, JsonValue>("Description", item.Description)
})
};
JsonArray returnValue = new JsonArray(jsonList);
return returnValue;
}