Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a string which contains some JSON object from ServiceStack

Tags:

I have the following DTO:

public class MyDTO
{
    public int Id { get; set; }

    public String Info { get; set; }
}

The Info element contains some serialized JSON object which can be of multiple different types. In my service function, I return this DTO using return x.ConvertTo<MyDTO>()

My problem is, that, since ServiceStack is not aware that Info holds a JSON, the special characters (quotation marks) of Info are escaped.

So I get

{"Id":15,"Info":"[\"Test1\",\"Test2\",\"Test3\"]"}

from the service, but what I would like to get is actually

{"Id":15,"Info":["Test1","Test2","Test3"]}

Is there some way, to tell ServiceStack that Info holds JSON data and thus prevent it from escaping the string and instead inserting the JSON value directly into the response?

P.S.: My question is not a duplicate of that question, which is concerned with forcing the default DTO encoding of a service to JSON, while my problem deals with how the JSON encoding happens for certain types.

like image 650
mat Avatar asked May 30 '17 09:05

mat


1 Answers

using composition you can interpret the Info property of MyDTO

public class MyDTO<T> : MyDTO {

    public MyDTO(MyDTO dto) {
        this.Id = dto.Id;
        this.Info = JsonConvert.DeserializeObject<T>(dto.Info);
    }

    public new T Info { get; set; }
}

that way the JSON value in Info can be normalized before returning it to be serialized.

For example

var dto = x.ConvertTo<MyDTO>();
return new MyDTO<dynamic>(dto);

If dto.Info was a JSON array of strings would allow the array to be serialized as desired in the OP

var dto = new MyDTO {
    Id = 15,
    Info = "[\"Test1\",\"Test2\",\"Test3\"]"
}

would produce

{"Id":15,"Info":"[\"Test1\",\"Test2\",\"Test3\"]"}

where as

new MyDTO<dynamic>(dto);

would produce

{"Id":15,"Info":["Test1","Test2","Test3"]}
like image 80
Nkosi Avatar answered Sep 25 '22 10:09

Nkosi