Jigar Shah
Jigar Shah

Reputation: 65

Convert json to C# classes with generic property

I have json data as below:

{
status: "success",
data: {
custid1: 723,
custid2: 670,
custid3: 430
}
}

As per https://json2csharp.com/, C# classes should be like below:

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
public class Data    {
    public int custid1 { get; set; } 
    public int custid2 { get; set; } 
    public int custid3 { get; set; } 
}

public class Root    {
    public string status { get; set; } 
    public Data data { get; set; } 
}

But I dont like Data class above, it has custid1, custid2 as hard coded. I know here json data is like that so classes are generated accordingly but can we make some generic design which can parse below line?

 var result = JsonConvert.DeserializeObject<Root>(json);

Upvotes: 0

Views: 609

Answers (1)

Dai
Dai

Reputation: 155035

I feel that tools like Json2CSharp.com are only intended for scaffolding and prototyping rather than for directly-usable C# code. So go ahead and use it to quickly create initial code for your project, but you likely will need to tweak it for production use - in this case one of those tweaks you need to make is to change data: entry in the Root DTO class from having its own class Data to being a Dictionary<String,Int32> instead so that it can accommodate the dynamic nature of the data: property in production JSON data.


Side-note: You should use PascalCase for all class properties in your C# code - but you can configure your JSON serializer to automatically map the camelCase properties in the JSON.

If you're using Newtonsoft.Json then use CamelCaseNamingStrategy or set an explicit [JsonProperty( "camelCaseName" )]. You don't even have to do this manually because JSON2CSharp.com can do it automatically for you:

It's in the Options menu next to the Convert button:

enter image description here

Upvotes: 3

Related Questions