Search code examples
c#jsonservicestackormlite-servicestackservicestack-text

How to serialize object to JSON using DataAnnotation to format double property using ServiceStack request


Using ServiceStack I need to format this request in order that the CodValue property stays in this format #.#

[DataContract(Name = "request1")]
public class Request1
{
   [DataMember(Name = "codValue")]
   public double CodValue { get; set; }
}

var request1 = new Request1 { CodValue = 0.0 }
_serviceClientBase.Post(request1);

However, when I send the request the server side receives CodValue = 0 But as the server side is Java, it returns an error saying that it is Java.Lang.Long and not Double.

How can I force ServiceStack to keep the JSON request in the format 0.0 ?


Solution

  • You can specify a JsConfig<T>.RawSerializerFn to append any missing .0 suffix, e.g:

    JsConfig<double>.IncludeDefaultValue = true;
    JsConfig<double>.RawSerializeFn = d =>
    {
        var str = d.ToString(CultureInfo.InvariantCulture);
        return str.IndexOf('.') >= 0 ? str : str + ".0";
    };
    

    To print the desired result:

    var dto = new Request1 { CodValue = 0.0 };
    
    dto.ToJson().Print(); //= {"codValue":0.0}