使用类和属性名称作为JSON中的输出

时间:2013-05-05 08:41:50

标签: json api servicestack

我有这个DTO:

public class Post
{
    public int Id { get; set; }
    public string Message { get; set; }
    public DateTime CreatedDate { get; set; }
}

然后我在servicestack中有一条返回此DTO列表的路由。 方法签名如下所示:public IList<Post> GetAllPost()

从这条路线获得结果时,我的json看起来像这样:

[3]
    0:  {
        Id: 2
        Message: "itworks1"
        CreatedDate: "/Date(1367264995010+0200)/"
    }-
    1:  {
        Id: 3
        Message: "itworks2"
        CreatedDate: "/Date(1367265002050+0200)/"
    }-
    2:  {
        Id: 4
        Message: "itworks3"
        CreatedDate: "/Date(1367265006767+0200)/"
}

但是我希望JSON输出看起来像这样:

posts
    post:  {
        Id: 2
        Message: "itworks1"
        CreatedDate: "/Date(1367264995010+0200)/"
    }-
    post:  {
        Id: 3
        Message: "itworks2"
        CreatedDate: "/Date(1367265002050+0200)/"
    }-
    post:  {
        Id: 4
        Message: "itworks3"
        CreatedDate: "/Date(1367265006767+0200)/"
}

使用servicestack序列化程序可以实现吗?

1 个答案:

答案 0 :(得分:1)

尝试将回复包装在对象中:

public class PostListResponse
{
    public List<Post> Posts { get; set; }
}
...
public PostListResponse GetAllPosts()

然后你的json应该是这样的:

{
    "posts":[
         { 
             "id":4,
             "message":"intworks3",
             "createdDate":"/Date((1367265006767+0200)/" 
         },
         { 
             "id":5,
             "message":"intworks4",
             "createdDate":"/Date((1367265006767+0200)/" 
         },
         ...
    ]
}