0

I have to deserialize json into C# classes but many of the json field names have a forward slash in them.

I've searched this site to see if anyone else has asked a similar question but nothing came up.

json:

  {
    "start": "2019-10-24T10:37:27.590Z",
    "end": "2019-10-24T11:00:00.000Z",
    "requests/duration": {
      "avg": 3819.55
    }
  }

c#

class Metrics
{
   public DateTime start = DateTme.MinValue;
   public DateTime end = DateTme.MinValue;
   public RequestsDuration requestsduration = null;
}

class RequestsDuration
{
   public double avg = 0.0;
}

...
Metrics data = JsonConvert.DeserializeObject<Metrics>(json);

The "requests/duration" in the json does not deserialize into the Metrics class.

I can do this before deserializing:

json = json.Replace("requests/duration","requestsduration")

but I was wondering if there was a cleaner way.

Does json.net provide a way to deal with special characters in json fields?

toni
  • 133
  • 1
  • 10
  • 3
    possible duplicate (https://stackoverflow.com/questions/15915503/net-newtonsoft-json-deserialize-map-to-a-different-property-name). I think what you are looking for is to decorate this `[JsonProperty("requests/duration")]` for your `public RequestsDuration requestsduration = null; }` – Ryan Wilson Oct 24 '19 at 17:04

1 Answers1

2

You can customize field names for the json by using JsonProperty attribute. For the Metrics class you can do following:

class Metrics
{
   public DateTime start = DateTme.MinValue;
   public DateTime end = DateTme.MinValue;
   [JsonProperty("requests/duration")]
   public RequestsDuration requestsduration = null;
}