Search code examples
jsonserializationservicestackdto

JSON property with hyphen in it in ServiceStack


I have some JSON formed like this:

 {
  "snippet-format":"raw",
  "total":1,"start":1,
  "page-length":200, ... 
 }

I have a C# DTO with members called Total, Start etc. These are successfully having the values from the above placed in to them. I don't know how to name properties for the snippet-format and page-length JSON items above though.

I've tried SnippetFormat and Snippet_Format to no avail.

Could someone please point me in the right direction.

Also, if a value happens to be a W3C xs:dateTime string, is there a type I can use that ServiceStack will automatically populate for me?

Thanks in advance.


Solution

  • Checked into the next version of ServiceStack.Text v3.9.43+, the Lenient property convention now supports hyphened properties, so you will be able to do:

    public class Hyphens
    {
        public string SnippetFormat { get; set; }
        public int Total { get; set; }
        public int Start { get; set; }
        public int PageLength { get; set; }
    }
    
    JsConfig.PropertyConvention = JsonPropertyConvention.Lenient;
    
    var json = @"{
        ""snippet-format"":""raw"",
        ""total"":1,
        ""start"":1,
        ""page-length"":200
     }";
    
    var dto = json.FromJson<Hyphens>();
    
    Assert.That(dto.SnippetFormat, Is.EqualTo("raw"));
    Assert.That(dto.Total, Is.EqualTo(1));
    Assert.That(dto.Start, Is.EqualTo(1));
    Assert.That(dto.PageLength, Is.EqualTo(200));
    

    In the meantime you will have to parse it dynamically, e.g:

    var map = JsonObject.Parse(json);
    Assert.That(map["snippet-format"], Is.EqualTo("raw"));
    Assert.That(map["total"], Is.EqualTo("1"));
    Assert.That(map["start"], Is.EqualTo("1"));
    Assert.That(map["page-length"], Is.EqualTo("200"));