Search code examples
c#restservicestackdto

ResponstDTO with complex Property in ServiceStack


Havin a Response with a complex property, i want to to map to my responseDTO properly. For all basic types it works out flawlessly.

The ResponseDTO looks like this:

public class ResponseDto
{
    public string Id {
        get;
        set;
    }

    public struct Refs
    {
        public Genre GenreDto {
            get;
            set;
        }

        public Location LocationDto {
            get;
            set;
        }
    }

    public Refs References {
        get;
        set;
    }
}

Genre and Location are both for now simple classes with simple properties (int/string)

public class GenreDto {

    public string Id {
        get;
        set;
    }
    public string Name {
        get;
        set;
    }

}

Question: Is there any way, without changing/replacing the generic unserializer ( and more specific example) (in this example JSON ) to map such complex properties? One specific difference to the GithubResponse example is, that i cant use a dictionry of one type, since i have different types under references. Thats why i use a struct, but this seems not to work. Maybe only IEnumerable are allowed?

Update There is a way using lamda expressins to parse the json manually github.com/ServiceStack/ServiceStack.Text/blob/master/tests/ServiceStack.Text.Tests/UseCases/CentroidTests.cs#L136 but i would really like to avoid this, since the ResponseDTO becomes kinda useless this way - since when writing this kind of manual mapping i would no longer us Automapper to map from ResponseDto to DomainModel - i though like this abstraction and "seperation".

Thanks


Solution

  • I used lambda expressions to solve this issue, a more complex example would be

    static public Func<JsonObject,Cart> fromJson = cart => new Cart(new CartDto {
            Id = cart.Get<string>("id"),
            SelectedDeliveryId = cart.Get<string>("selectedDeliveryId"),
            SelectedPaymentId = cart.Get<string>("selectedPaymentId"),
            Amount = cart.Get<float>("selectedPaymentId"),
            AddressBilling = cart.Object("references").ArrayObjects("address_billing").FirstOrDefault().ConvertTo(AddressDto.fromJson),
            AddressDelivery = cart.Object("references").ArrayObjects("address_delivery").FirstOrDefault().ConvertTo(AddressDto.fromJson),
            AvailableShippingTypes = cart.Object("references").ArrayObjects("delivery").ConvertAll(ShippingTypeDto.fromJson),
            AvailablePaypmentTypes = cart.Object("references").ArrayObjects("payment").ConvertAll(PaymentOptionDto.fromJson),
            Tickets = cart.Object("references").ArrayObjects("ticket").ConvertAll(TicketDto.fromJson)
        });
    

    So this lamda exprpession is used to parse the JsonObject response of the request and map everything inside, even nested ressources. This works out very well and flexible