Спасибо за проверку моего вопроса.В настоящее время я пытаюсь создать JSON, в котором у меня есть URL, ссылки и заголовок.Для классической, типичной (даже избитой) нумерации страниц с использованием AJAX.
(Сначала я создал json с использованием Newton, но получил JSON с кодами, такими как \ r \ n, потому что, согласно одному сообщению StackOverflow, ASP.NET по умолчанию заботится об этом, поэтому с помощью Newton я сделал это дважды, отсюда и коды новой строки и прочее.)
Итак, я пытаюсь создать соответствующий файл JSON в форме объекта словаря, изатем поместите это в return json (..., ....) в конце.
Тип json, который я хочу, выглядит следующим образом:
[
"newsItems":
[
{
"url":"/foofoo/kebab",
"title":"kebab is yummy",
"img":"/img/soKebab/png",
...
},
{
"url":"/foofoo/dimsum",
...
}
...
],
"control":
[
"hasNext":false,
"currentPage": 3,
"hasPrevious":true
]
]
и для этого я написал следующее.Он наследует Umbraco.Web.Mvc.SurfaceController.
public ActionResult Pagination(int? page)
{
//instantiate five ipublishedcontents to create the json.
IEnumerable<IPublishedContent> newsPostsToRender = Umbraco.TypedContent("*id*").OrderByDescending(x =>x.UpdateDate).Skip((page.GetValueOrDefault(1) - 1) * 5).Take(5);
//instantiate an object that is going to be formed into a json and sent back to the client.
ListDictionary jsonToBeSent = new ListDictionary();
Dictionary<string, ListDictionary> newsItemsList = new Dictionary<string, ListDictionary>();
//fill and create values for "newsItems"
foreach (IPublishedContent item in newsPostsToRender)
{
//we are going to assign an array to the value of a dictionary object. So let's create the value first.
ListDictionary newsItem = new ListDictionary();
newsItem.Add("thumbnail", Umbraco.Media(item.GetPropertyValue<int>("thumb")).Url);
newsItem.Add("title", item.Name);
newsItem.Add("linkToPost", item.Url);
newsItem.Add("lastUpdate", item.UpdateDate.ToString("yyyy/MM/dd"));
//finally, I want to assign the newsItem object to newsItemsList, with its key being "newsItems"
//but I'm getting an error saying "this key already exists" whatever string I put for the key. (even gibberish such as aoihfdoasdhfa)
foreach (System.Collections.DictionaryEntry i in newsItem)
{
//Display what is assigned to newsItem to make sure the problem doesn't lie here.
System.Diagnostics.Debug.WriteLine("this is newsItem:\r\n" + i.Value);
}
System.Diagnostics.Debug.WriteLine("newsItemsList"+newsItemsList.ToString());
foreach (KeyValuePair<string, ListDictionary> ii in newsItemsList)
{
//★★★Display what is assigned to newsItemList (I think it's either null or empty), because it keeps on saying I already have whatever value I specify.★★★
System.Diagnostics.Debug.WriteLine("this is newsItemsList:\r\n" + ii.Value.Values.ToString());
if (ii.Value.Values ==null)
{
System.Diagnostics.Debug.WriteLine("this is newsItemsList is null");
}
}
//and this is the troublemaker.
newsItemsList.Add("newsItems", newsItem);
}
//next add the control element (in the form of array), and throw it back to the client.
return Json(jsonToBeSent, JsonRequestBehavior.AllowGet);
}
и вопрос в том, что я получаю сообщение об ошибке для следующей части.
newsItemsList.Add("newsItems", newsItem);
он говорит: «этот ключ ужесуществует "любая строка, которую я использую в качестве ключа.Поэтому я написал несколько System.Diagnostics.Debug.WriteLine ();прямо перед этим.и там говорится, что «newsItemsList» выглядит следующим образом (отображается в строке записи с ★★★ выше)
newsItemsListSystem.Collections.Generic.Dictionary`2[System.String,System.Collections.Specialized.ListDictionary]
this is newsItemsList:
System.Collections.Specialized.ListDictionary+NodeKeyValueCollection
Мой вопрос:
(1), что такое «NodeKeyValueCollection» (cannне могу найти документацию, которую вы могли бы найти для обычных классов, когда я гуглил ее, она дала мне фактический исходный код)
(2) что это за "+" (означает сцепленный ??)
(3) как посмотреть, что внутри?(есть ли способ ...?)
(4) почему я получаю это ??
Спасибо,