【问题标题】:Not Getting the Root Name in JSON Format using WCF Rest未使用 WCF Rest 获取 JSON 格式的根名称
【发布时间】:2012-06-20 07:47:49
【问题描述】:

我没有得到任何 Json 格式的根值。 我收到如下回复:

[{"Username":"demo","UserID":8,"Password":"demo","EmaiID":"demo@gmail.com"}]

我想要的格式如下

{UserList: [[{"Username":"demo","UserID":8,"Password":"demo","EmaiID":"demo@gmail.com"}]}

服务声明:

public interface IDemo
{  
    [OperationContract]
    [WebInvoke(RequestFormat = WebMessageFormat.Json,ResponseFormat =
    WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "/Validate", Method = "POST")]
    Stream ValidateUser(Login obj);

}

[DataContract]
public class Login
{

    public Login()
    {
    }

    [DataMember]
    public string Username { get; set; }
    [DataMember]
    public string Password { get; set; }
}

服务定义:

public class Demo: IDemo
{
    string Json = string.Empty;

    JavaScriptSerializer obj1 = new JavaScriptSerializer();

    public Stream ValidateUser(Login obj)
    {

        UserList objUserList = new UserList();
        Users objUser = new Users();
        objUser.Username = obj.Username;
        objUser.Password = obj.Password;

        objUserList = LoginDataService.ValidateUser(objUser.Username,objUser.Password) ;

        if (objUserList.Count > 0)
        {
            Json = obj1.Serialize(objUserList);
            WebOperationContext.Current.OutgoingResponse.ContentType =  
            "application/json; charset=utf-8"; 
        }
        else
        {
            UserError objError = new UserError();

            objError.ErrMsg = "LoginFailed";objError.Username = objUser.Username ;

            Json = obj1.Serialize(objError);

            WebOperationContext.Current.OutgoingResponse.ContentType = 
            "application/json; charset=utf-8";
        }

        return new MemoryStream(Encoding.UTF8.GetBytes(Json));  
    }
}

谁能帮我得到根元素的结果,让我知道我犯了什么样的错误。

感谢和问候, 维杰

【问题讨论】:

    标签: json wcf rest


    【解决方案1】:

    由于您将集合序列化为 JSON,因此您将获得类似的格式。您可以返回一个将列表包装为属性的类,然后您将得到您想要的。

    例如。你可以创建一个这样的类

    public class UserListResponse
    {
       public UserList UserList{get; set;}
    } 
    

    现在你得到了你所期望的 JSON,比如

    {UserList:[..]}
    

    我不明白你为什么要返回一个 Stream 并自己做所有的序列化框架,基本上这一切都是由框架完成的。您所要做的就是从服务方法返回包装类UserListResponse

    public class Demo: IDemo
    {
       public UserListResponse ValidateUser(Login obj)
       {
          ...
          return new UserListResponse{ UserList = objUserList};
       }
    }
    

    WCF 将负责将结构返回为 JSON 或 XML,您无需担心。

    【讨论】:

    • 这里唯一需要注意的是返回类型与方法签名匹配
    【解决方案2】:

    虽然上述解决方案非常有效,但您也可以尝试在您的方法中使用 WebInvoke 属性的参数 BodyStyle=WebMessageBodyStyle.WrappedResponse。

    这将值包装在类型名称中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多