使用LINQ to JSON前,需要引用Newtonsoft.Json的dll和using Newtonsoft.Json.Linq的命名空间。LINQ to JSON主要使用到JObject, JArray, JProperty和JValue这四个对象,
JObject用来生成一个JSON对象,简单来说就是生成”{}”,
JArray用来生成一个JSON数组,也就是”[]”,
JProperty用来生成一个JSON数据,格式为key/value的值,
而JValue则直接生成一个JSON值
System.Data.DataTable dt = Owlfood.LogicService.Users.TransactionLogGroupByDate(userId);
if (dt != null && dt.Rows.Count > 0)
{
JObject resultJson = new JObject(new JProperty("messages", CommonLibrary.ErrorMessage.CodeToMessage(1)), new JProperty("code", 1));
resultJson.Add(new JProperty("group", (JArray)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(dt))));
//result = "{\"messages\": \"" + CommonLibrary.ErrorMessage.CodeToMessage(1) + "\",\"code\": 1, \"group\": ";
//result+=JsonConvert.SerializeObject(dt);
//result += "}";
//JObject resultJson = (JObject)JsonConvert.DeserializeObject(result);
for (int times=0; times<dt.Rows.Count; times++)
{
string shortDate = dt.Rows[times]["shortDate"].ToString();
System.Data.DataTable list = Owlfood.LogicService.Users.TransactionLogByDatePage(userId, shortDate, 0, 1,100000);
if (list != null && list.Rows.Count > 0)
{
//string values = JsonConvert.SerializeObject(list);
JArray jo1 = (JArray)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(list));
JObject a1 = (JObject)resultJson["group"][times];
a1.Add(new JProperty("list", jo1));
}
}
result = resultJson.ToString();
}
else
{
result= "{\"messages\": \"" + CommonLibrary.ErrorMessage.CodeToMessage(-1) + "\",\"code\": -1}";
}