Search code examples
servicestackormlite-servicestack

Value structs in DTOs in ServiceStack


I there a way to get proper serialization of structs in DTO's or better yet have the framework somehow treat the structs as dto's.

I have been informed of the JsConfig.TreatValueAsRefTypes value but that would just work for json am I right? what about xml, soap, mq ect... I simply want to use the structs I have an not have to map them to dto's which for my project would take years...

On the side not I also cant figure out what im doing wrong with JsConfig.TreatValueAsRefTypes the compiler seems to think its being called in static context: An object reference is required for the non-static field, method...


Solution

  • I've just committed a change (available in the next release) that makes JsConfig<T>.TreatValueAsRefType as static so you can now serialize struct types as a reference type, e.g:

    public struct UserStruct
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    JsConfig<UserStruct>.TreatValueAsRefType = true;
    
    var dto = new UserStruct { Id = 1, Name = "foo" };
    
    dto.ToJson().Print(); //= {"Id":1,"Name":"foo"}
    
    dto.ToJsv().Print();  //= {Id:1,Name:foo}
    
    dto.ToXml().Print(); 
    

    ServiceStack uses .NET's XML DataContractSerializer (which is also used in SOAP) which already serializes structs as expected with:

    <?xml version="1.0" encoding="utf-8"?>
    <UserStruct xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns="http://schemas.datacontract.org/2004/07/ServiceStack.Text.Tests">
        <Id>1</Id>
        <Name>foo</Name>
    </UserStruct>
    

    You can also use the static API to register struct types using the non-generic API:

    JsConfig.TreatValueAsRefTypes.Add(typeof(UserStruct));