簡體   English   中英

將額外的JSON對象添加到Web API響應

[英]Adding an extra JSON Object to the Web API Response

我需要將額外的JSON對象附加到Web API方法生成的JSON響應中。 例如:

我的代碼現在:

[Route("api/getcomnts")]
public IHttpActionResult GetCommentsForActivity(string actid)
{
       List<Comment> cmntList = CC.GetAllComments(actid);
       return Ok(cmntList);
}

如果評論成功檢索,我想發送:

“狀態”:“成功”

以及它已作為JSON數組發送的注釋列表。

要么

“狀態”:“失敗”

如果評論列表是EMPTY。 是否可以將這個名為JSON的額外JSON對象附加到我現有的方法中?

這將使我的客戶端Android和iOS應用程序非常方便:)

編輯

或者對於這樣的場景:

    [HttpGet]
    [Route("api/registeruser")]
    public IHttpActionResult RegisterUser(string name, string email, string password)
    {

        int stat = opl.ConfirmSignup(name, email, password);
        string status = "";
        if (stat == 0)
        {
            status = "fail";
        }
        else
        {
            status = "success";
        }
        return Ok(status);
    }

您可以使用Web API返回匿名對象。

    [Route("api/getcomnts")]
    public IHttpActionResult GetCommentsForActivity(string actid)
    {
           List<Comment> cmntList = CC.GetAllComments(actid);
           var success = cmntList.Count() > 0 ? "success" : "success";
           return Ok(new { List = cmntList, success } );
    }

**EDIT:**

    [Route("api/getcomnts")]
    public IHttpActionResult GetCommentsForActivity(string actid)
    {
           List<Comment> cmntList = CC.GetAllComments(actid);
           string status = "";
           if(cmntList.Count()!=0)
           {
                status = "success";
           }
           else
           {
                status = "fail"; 
           }
           return Ok(new { List = cmntList, status } );
    }

你可以試試這個

public HttpResponseMessage Get(string actid)
    {
        //sample..
        if (value == true)
            return Request.CreateResponse(HttpStatusCode.OK, getStatus("success"), JsonMediaTypeFormatter.DefaultMediaType);
        else
            return Request.CreateResponse(HttpStatusCode.OK, getStatus("failed"), JsonMediaTypeFormatter.DefaultMediaType);
    }

    private object getStatus(string s)
    {
        var status = new { Status = s };
        return status;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM