本文介绍了要的System.IO.Stream数据传输对象之前,WCF REST序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是建立在前面一个问题(虽然题外话)的。
请先不妨一读

This question builds upon an earlier question (although off-topic) I asked yesterday. Please give it a read first.

确定 - 在我的WCF REST的项目,我已经转换我的域对象数据传输对象(DTO的)前JSON序列化到移动客户端。例如,这里是我的用户DTO:

OK - in my WCF REST project, I have been converting my domain objects to data transfer objects (DTOs) prior to JSON serialization to mobile clients. For example, here is my User DTO:

[DataContract]
public class UserDto
{
    [DataMember]
    public string UserId { get; set; }

    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Email { get; set; }

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

}

和我User.svc的服务,UserDto得到序列化返回给客户端为这样的:

And in my User.svc service, the UserDto gets serialized back to the client as such:

 public UserDto GetUserById(string userid)
        {
            var obj = UserRepository.GetUserById(userid);
            return new Contracts.UserDto
            {
                Email = obj.Email.ToString(),
                Password = obj.Password.ToString(),
                UserId = obj.UserId.ToString(),
                UserName = obj.UserName.ToString()
            };
        }

现在,我有一个基类,公开以下方法>

Now, I have a base class that exposes the following method:

public virtual Stream GetGroupById(string id)

我Dashboard.svc服务。它返回如下:

to my Dashboard.svc service. It returns the following:

return new MemoryStream(bytes);

在这个服务,我想覆盖的方法和返回
结果到客户端在我序列化我的上述UserDto以同样的方式。

In this service, I want to override the method and returnthe results to the client in the same way that I am serializing my above UserDto.

我的问题是 - 你怎么转换型流的方法,为数据传输对象和序列化的结果(作为JSON格式字符串)到客户端???

MY QUESTION IS - how do you convert a method of type Stream into a Data transfer object and serialize the results (as a JSON-formatted string) to the client???

感谢您的帮助。

推荐答案

我可能是错的理解的东西在这里,但你想要做的是倒退。你会先得到你的域对象,然后转换为DTO,然后写连载DTO到流:

I might be mis-understanding things here, but what you're trying to do is backwards. You would first get your domain object, then convert to the DTO, then write the serialized DTO to the stream:

public virtual Stream GetGroupById(string id)
{
    var user = UserRepository.GetUserById(id);
    var dto = new Contracts.UserDto
              {
                  Email = user.Email.ToString(),
                  Password = user.Password.ToString(),
                  UserId = user.UserId.ToString(),
                  UserName = user.UserName.ToString()
              }

    var serializer = new JavaScriptSerializer()l
    var bytes = Encoding.UTF8.GetBytes(serializer.Serialize(dto));

    return new MemoryStream(bytes);
}



的流被返回到客户机将包含JSON进行序列化DTO。

The Stream being returned to the client will contain the JSON for the serialized DTO.

这篇关于要的System.IO.Stream数据传输对象之前,WCF REST序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 16:33