我正在尝试在我的 Razor 视图中直接输出 JSON。被序列化的对象是IEnumerable<ItemDto>
(见下面的定义)。我想将它序列化为从ApiController
. 这是我尝试过的:
- 使用 时
@Json.Encode(theValue)
,它会忽略DataMember
,因此属性名称错误(首字母大写)。 - 使用
DataContractJsonSerializer
(并将其转换IEnumerable<ItemDto>
为IList<ItemDto>
)时,它输出ImageDto.Sizes
as[{ Key: 'foo', Value: <object> }]
,但 ApiController 正确地输出{ 'foo': <object> }
。
这是我的课程:
[DataContract]
public class ItemDto
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "image")]
public ImageDto Image { get; set; }
[DataMember(Name = "price")]
public decimal Price { get; set; }
}
[DataContract]
public class ImageDto
{
[DataMember(Name = "id")]
public Guid Id { get; set; }
[DataMember(Name = "sizes")]
public Dictionary<String, ImageSizeDto> Sizes { get; set; }
}
[DataContract]
public class ImageSizeDto
{
[DataMember(Name = "url")]
public string Url { get; set; }
[DataMember(Name = "w")]
public int Width { get; set; }
[DataMember(Name = "h")]
public int Height { get; set; }
}
目的是避免GET
在几乎每个页面上都需要单独请求数据。
所需的 JSON:
[{"id":6,
"title":"Foo bar baz",
"image":
{"id":"fb2a3b4a-5ae5-4d9d-baff-72e107aa6e9c",
"sizes":
{"Original": {"url":"http://example.com/a", "w":-1, "h":-1},
"Thumbnail": {"url":"http://example.com/b", "w":130, "h":73},
"LargeThumbnail": {"url":"http://example.com/c", "w":220,"h":124},
"Popup": {"url":"http://example.com/d", "w":256, "h":256},
"FullWidth": {"url":"http://example.com/e", "w":930, "h":524}}},
"price":79}]