How to get value from JSON object in c#? If the key is not defined

Below is my JSON information where you can notice that there is not any key defined.

{"KOA": {"test.jpg": "xyz.com/images/test.jpg"}}

I am Looking the Output like:

string _imgName=  ms-koa-acazia-ceramic.jpg
string _imgUrl= xyz.com/images/test.jpg

“KOA” is also a dynamic value it can be changed so I can not fix it.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

One approach you can use to achieve this is to use dictionaries to deserialize the JSON object

        const string jsonString = "{"KOA": { "test.jpg": "xyz.com / images / test.jpg"}}";
        var jsonObject = JsonConvert.DeserializeObject<IDictionary<string, IDictionary<string, string>>>(jsonString);

        string firstKey = jsonObject.Keys.First();

        string _imgName = jsonObject[firstKey].Keys.First();
        string _imgUrl = jsonObject[firstKey].Values.First();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x