2014-12-05 72 views
0

在我的應用程序的默認JSON結果從返回的WebAPI是像這個 -如何從以特定格式的WebAPI JSON響應

[{"Id":1,"Name":"Nayas","Email":"[email protected]"}, {"Id":2,"Name":"Ramesh","Email":"[email protected]"}]. 

我想這是在下面的格式

{ 
"success": true, 
"users": [ 
    {"id": 1, "name": 'Ed', "email": "[email protected]"}, 
    {"id": 2, "name": 'Tommy', "email": "[email protected]"} 
] 
} 

鍵值對

這裏是我的操作方法

public IEnumerable<User>GetUserList() 
{ 
    return userlist; 
} 

和我的模型

public class User 
{ 
    [Key] 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Email { get; set; } 
} 
+0

您可以顯示您的Web API的操作方法以及您要返回的模型的定義嗎? – 2014-12-05 10:22:24

+0

public class User {Key35] public int Id {get;組; } public string Name {get;組; } public string Email {get;組; } } – 2014-12-05 10:26:32

+0

public IEnumerable GetUserList(){return userlist}。我們可以使用keyvalue對 – 2014-12-05 10:27:45

回答

1

如果你想你的JSON格式是在一個特定的方式,那麼所有你需要做的是確保你的C#(或您選擇的.net語言)與您想要查看的內容相匹配。

在您的例子則JSON:

{ 
"success": true, 
"users": [ 
    {"id": 1, "name": 'Ed', "email": "[email protected]"}, 
    {"id": 2, "name": 'Tommy', "email": "[email protected]"} 
] 
} 

會是這樣表示:

public class YourRootObjectName 
{ 
    public bool Success {get;set;} 
    public IEnumberable<User> Users {get;set;} 
} 

public class User 
{ 
    public int Id {get;set;} 
    public string Name {get;set;} 
    public string Email {get;set;} 
} 

然後你有你的值映射到這個結構。發佈您的WebApi控制器代碼以及您正在使用的DTO類,這將更加清楚您要實現的目標。

+0

謝謝你這個作品 – 2014-12-05 10:56:41

1

如果你想回到這種JSON的最好的辦法是返回包含一個成功的指示和用戶列表中選擇一個單獨的模型。

public class ResponseModel 
{ 
    public bool Success { get; set; } 
    public IEnumerable<User> Users { get; set; } 
} 

你的操作方法可能再是這樣的:

public ResponseModel GetUserList() 
{ 
    var response = new ResponseModel { Success = true, Users = userlist }; 
    return response; 
}