Search code examples
c#jsonjson.netdeserializationjson-deserialization

Map (deserialize) JSON API result that contains the object's properties as a numbered list


I've searched SO and google for a similar question, but couldn't find the exact thing I'm searching for.

I'm developing an application that queries an API that returns the following result:

{
    "Ticket": {
        "1": {
            "DisplayName": "Ticket ID",
            "Value": 117
        },
        "2": {
            "DisplayName": "Last Modified",
            "Value": "2022-10-05T18:09:32.1070000Z"
        },
        "3": {
            "DisplayName": "Last User",
            "Value": "SYSTEMACCOUNT"
        },
        "4": {
            "DisplayName": "Seq_Group",
            "Value": 1
        },
        ...
    }
}

And I want to deserialize it to an object like the following:

public class Ticket 
{
    public property int TicketID {get; set;}
    public property DateTime LastModified {get; set;}
    public property string LastUser {get; set;}
    public property int Seq_Group {get; set;}
}

(there are several more properties hidden here for brevity)

Can you point me in the direction of how to do the mapping in the best way?

I know I could deserialize it to a Dictionary and then iterate the dictionary with several ifs and elses, but I think there must be a smarter way to solve it.

Thanks!


Solution

  • you need only one line of code

    Ticket ticket =  new JObject( ((JObject)JObject.Parse(json)["Ticket"]).Properties()
          .Select(t=> new JProperty((string) t.Value["DisplayName"], t.Value["Value"])))
          .ToObject<Ticket>();
    

    and fix your class

    public class Ticket
    {
        [JsonProperty("Ticket ID")]
        public int TicketID { get; set; }
        
        [JsonProperty("Last Modified")]
        public DateTime LastModified { get; set; }
        
        [JsonProperty("Last User")]
        public string LastUser { get; set; }
        
        public int Seq_Group { get; set; }
    }