0

I have Json coming from an api and i want to Deserialize it into an object, however the json looks like this:

{
  "ticket_metric": {
   some json fields etc
}

I have a class that maps to the objects inside the ticket_metric, how do i map to it without having to create a root object with a ticket_metric field inside it.

Hawkzey
  • 1,088
  • 1
  • 11
  • 21
  • 1
    Deserialize to a dictionary, ie. something like `JsonConvert.DeserializeObject>(json)`. – Lasse V. Karlsen Aug 17 '19 at 20:29
  • @LasseVågsætherKarlsen that is a good idea :), but is there not a better way using attributes i cant seem to find one >.<. – Hawkzey Aug 17 '19 at 20:36
  • Well, you can create a root type with a property, and then use an attribute, `[JsonProperty("ticket_metric")]`. – Lasse V. Karlsen Aug 17 '19 at 20:44
  • @LasseVågsætherKarlsen that is exactly what im trying to avoid XD, i dont want to create a whole new object. – Hawkzey Aug 17 '19 at 20:50
  • Then you deserialize into a dictionary. – Lasse V. Karlsen Aug 17 '19 at 20:53
  • 1
    Or you use `JObject.Parse(json)`, and then go grab the internal object using its indexer, like `obj["ticket_metric"].ToObject()`. – Lasse V. Karlsen Aug 17 '19 at 20:55
  • 1
    if you don't want to use a dictionary, and the name `ticket_metric` is known in advance, use an anonymous type: `JsonConvert.DeserializeAnonymousType(json, new { ticket_metric = default(TicketMetricType) } ).ticket_metric` as shown in [this answer](https://stackoverflow.com/a/53636937/3744182) to [Parse JSON without declaring model class](https://stackoverflow.com/q/53636516/3744182). – dbc Aug 17 '19 at 20:55
  • Deserializing to an anonymous type or a dictionary will be more performant than the `JObject.Parse(json)` + `obj["ticket_metric"].ToObject()` combination because the latter requires the JSON be completely loaded into an intermediate `JToken` hierarchy. – dbc Aug 17 '19 at 21:22

0 Answers0