简体   繁体   中英

How to deserialize this type of Json to C# object

"firstChainPrices":{
"Prices":[
{
"minPrice":"29250.00",
"currency":"KZT",
"brand":"DV.CITDMB.Y.3.OPT",
"minPriceAvailable":4,
"artificialPriceForChain":"29250.00"
},
{
"minPrice":"24950.00",
"currency":"KZT",
"brand":"DV.CITDMB.Y.1.LIGHT",
"minPriceAvailable":4,
"artificialPriceForChain":"24950.00"
},
{
"minPrice":"37350.00",
"currency":"KZT",
"brand":"DV.CITDMB.Y.5.FLEX",
"minPriceAvailable":4,
"artificialPriceForChain":"37350.00"
}
],
"Prices":[
{
"minPrice":"39118.00",
"currency":"KZT",
"brand":"DV.CITDMB.Y.3.OPT",
"minPriceAvailable":4,
"artificialPriceForChain":"39118.00"
},
{
"minPrice":"28148.00",
"currency":"KZT",
"brand":"DV.CITDMB.Y.1.LIGHT",
"minPriceAvailable":4,
"artificialPriceForChain":"28148.00"
},
{
"minPrice":"53643.00",
"currency":"KZT",
"brand":"DV.CITDMB.Y.5.FLEX",
"minPriceAvailable":4,
"artificialPriceForChain":"53643.00"
}
]

} I want to deserialize this json to C# object. But this json contains different Prices array (2 in this case) but when I am deserializing I am getting only one Price array. This is not a complete json I have given here (I have removed some parts because json is too long)

while it is not the most elegant solution this can solve your problem. And with a bit of work it can be generalized if you need.

    private string fix(string Json, string JsonKey)
    {
        string Key = "\"" + JsonKey + "\":";
        Regex r = new Regex(Key);
        int i = 0;
        while (Json.Contains(Key)) {
            string NewKey = Key.Replace("\":", i.ToString().Trim() + "\":");
            Json = r.Replace(Json, NewKey, 1);
            i++;
        }
        return Json;
    }

Similarly, you could consider merging all lists under the given key. To have only 1 price list.

Cheers

ps: Generalizing this to correct any arbitrary duplicate key at the same section, requires that you keep track of the sections... Which would be a rather painful procedure. So if it is only Prices that causes you the problem and it doesnt appear elsewhere as a key this is a an easy simple fix;-)

ps2: Ohh in case it was not clear... I replace each "Key" to "Key0", "Key1" etc... When you deserialize you should make a code that checks all entries and probably in your case merge them.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM