我需要在C#中创建一些JSON,格式如下:
{
"id": 10,
"items": [
{
"text": "Link 1",
"attr": { "href": "/somepage" },
"menuId": 20
},
{
"text": "Link 1",
"attr": { "href": "/someotherpage", "class": "test" },
"menuId": 21
}
]
}
我创建了一个基于一系列对象创建字符串的Web服务。首先,我的对象:
public class MenuItems
{
public string Id { get; set; }
public List<MenuItem> Items { get; set; }
}
和
public class MenuItem
{
public MenuItem()
{
this.Attr = new Dictionary<string, string>();
}
public string Text { get; set; }
public Dictionary<string, string> Attr { get; set; }
public string MenuId { get; set; }
}
要以小写字母获取属性名称,我有一个简单的合约解析器:
public class LowercaseContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
return propertyName.ToLower();
}
}
然后,我的代码来构建我的对象:
var list = new List<MenuItem>();
var children = //a call to our CMS api
foreach (var child in children)
{
var menuItem = new MenuItem();
menuItem.Text = child.PageName;
menuItem.MenuId = child.ContentLink.ID.ToString(CultureInfo.InvariantCulture);
menuItem.Attr.Add("href", urlResolver.GetUrl(child.ContentLink));
menuItem.Attr.Add("data-id-test", "Dave");
list.Add(menuItem);
}
var obj = new MenuItems {Id = id, Items = list};
var json = JsonConvert.SerializeObject(obj,
new JsonSerializerSettings() {ContractResolver = new LowercaseContractResolver()});
return json;
返回的JSON如下所示:
&#34; {\&#34; ID为\&#34;:\&#34; 69 \&#34; \&#34;项目\&#34;:[{\&#34 ; text \&#34;:\&#34;列出媒体\&#34;,\&#34; attr \&#34;:{\&#34; href \&#34;:\&#34 ; /页换测试/新闻和媒体/上市媒体/ \&#34;,\&#34;数据-ID测试\&#34;:\&#34;戴夫\&#34 ;},\&#34; menuid \&#34;:\&#34; 179 \&#34;},{\&#34; text \&#34;:\&#34;列表页面日期\ &#34; \&#34; ATTR \&#34;:{\&#34; HREF \&#34;:\&#34; /页换测试/新闻和媒体/ listing-页日期/ \&#34; \&#34;数据-ID-测试\&#34;:\&#34;戴夫\&#34;},\&#34; MENUID \&#34; :\&#34; 176 \&#34;},{\&#34; text \&#34;:\&#34;列出子页面\&#34;,\&#34; attr \&# 34;:{\&#34; HREF \&#34;:\&#34; /页换测试/新闻和媒体/挂牌子页/ \&#34;,\&#34 ;数据-ID-测试\&#34;:\&#34;戴夫\&#34;},\&#34; MENUID \&#34;:\&#34; 173 \&#34;}, {\&#34; text \&#34;:\&#34;新闻稿\&#34;,\&#34; attr \&#34;:{\&#34; href \&#34; :\&#34; /页换测试/新闻和媒体/新闻稿/ \&#34; \&#34;数据-ID-测试\&#34;:\&#34;戴夫\&#34;},\&#34; MENUID \&#34;:\&#34; 70 \&#34;}]}&#34;
哪个不被视为有效的JSON,但我真的不确定为什么。我的合同用JSON响应格式装饰,例如:
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "json/{id}")]
string DoWork(string id);
如果我将JSON响应粘贴到http://codebeautify.org/view/jsonviewer,它会声明整个字符串只是一个数组。 Firefix告诉我它是一系列个性化角色,所以显然我做错了。
有没有人有任何想法?