I have a json data like below with the same Image structure and different color names.
{
"colorImages":{
"Giraffe-safari Sand": [
{
"large": "...jpg",
"thumb": "...jpg",
"hiRes": "...jpg",
"main": {
"...jpg": [ "862", "679" ],
"...jpg": [ "434", "342" ],
"...jpg": [ "663", "522" ]
}
},
{
"large": "...jpg",
"thumb": "...jpg",
"hiRes": "...jpg",
"main": {
"...jpg": [ "606", "398" ],
"...jpg": [ "500", "328" ]
}
}],
"Pawprint - Burgundy": [
{
"large": "...jpg",
"thumb": "...jpg",
"hiRes": "...jpg",
"main": {
"...jpg": [ "862", "679" ],
"...jpg": [ "434", "342" ],
"...jpg": [ "663", "522" ]
}
},
{
"large": "...jpg",
"thumb": "...jpg",
"hiRes": "...jpg",
"main": {
"...jpg": [ "606", "398" ],
"...jpg": [ "500", "328" ]
}
}]
}
}
My model class:
public partial class Aa
{
[JsonProperty("colorImages")]
public Images ColorImages { get; set; }
}
public partial class Images
{
[JsonProperty("Giraffe-safari Sand")]
public List<ImageItem> GiraffeSafariSand { get; set; }
[JsonProperty("Pawprint - Burgundy")]
public List<ImageItem> PawprintBurgundy { get; set; }
}
public partial class ImageItem
{
[JsonProperty("large")]
public Uri Large { get; set; }
[JsonProperty("thumb")]
public Uri Thumb { get; set; }
[JsonProperty("hiRes")]
public Uri HiRes { get; set; }
[JsonProperty("variant")]
public string Variant { get; set; }
[JsonProperty("main")]
public Dictionary<string, List<long>> Main { get; set; }
}
How can I use Jsonconverter for dynamic property name so that I dont need to repeat [JsonProperty("Giraffe-safari Sand")] and [JsonProperty("Pawprint - Burgundy")] because there will be thousands of color name to handle.
To make a custom, dynamic item name and value(s), you can use a Dictionary:
[JsonProperty("Images")]
public Dictionary<string, List<ImageItem>> Images { get; set; }
You can use JSonConvert
method from Microsoft.Json
. Edit your object like this.
public class Aa
{
[JsonProperty("colorImages")]
public Dictionary<string, List<ImageItem>> Images { get; set; }
}
public class ImageItem
{
[JsonProperty("large")]
public Uri Large { get; set; }
[JsonProperty("thumb")]
public Uri Thumb { get; set; }
[JsonProperty("hiRes")]
public Uri HiRes { get; set; }
[JsonProperty("variant")]
public string Variant { get; set; }
[JsonProperty("main")]
public Dictionary<string, List<long>> Main { get; set; }
}
And in you conversion code :
var deserializedSrc = JsonConvert.DeserializeObject<Aa>(src);
You will have a dictionary which keys will be Giraffe-safari Sand
, Pawprint - Burgundy
etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.