DeepToot
DeepToot

Reputation: 79

Converting dynamic element string in JSON into a class

I could not find a question that deals with what I am about to ask so I went ahead and created this question.

I have a json coming back to me from our UI and I can convert that to an object without any issues until I hit this line:

\"lang\":{\"en-US\":{\"name\":\"AS Test Assembly Activity\",\"description\":\"Activity to test assembly activities\"}}

My problem is the "en-US" it appears it would be a class with fields of 'name' and 'description'. How can I safely convert the "en-US" to an object? This can be dynamic and will be whatever the culture code is set too.

I was able to get it converted by changing it to this:

\"lang\":{\"culture\":\"en-US\",\"name\":\"AS Test Assembly Activity\",\"description\":\"Activity to test assembly activities\"}}

But now the UI is stating they could use this, but prefer it to be inline with the original json.

Any thoughts?

Thanks

Edit: (What so I mean 'convert "en-US" to a class?)

when I convert this to a class it should look simliar to this:

public class CustomActivityLanguageData
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string Culture { get; set; }
}

But the Culture was added for the 'fix' I put in above. On the original json I posted, it looks like "en-US" would be a class in the same way that the 'CustomActivityLanguageData' class in code above is a class (btw 'CustomActivityLanguageData' == 'lang' in json)

It appears "en-US" has fields attached to it, like a class but it won't convert.

Double Edit: To further expound on this, it appears this is what the class would ultimately look like:

public class Lang
{
    en-US cultureCode {get;set;}
}

public class en-US
{
    public string name {get;set;}
    public string description {get;set;}
}

Hope that explains a little better.

Upvotes: 0

Views: 89

Answers (1)

gnasher729
gnasher729

Reputation: 52530

You need to realise what you are getting here. You received a dictionary (in JSON, it is called an 'object'). One of the keys in the dictionary is "lang". The value for the "lang" key is itself a dictionary. It could have many keys, probably for different languages, but you received only one key named "en-US". And the value for that key is again a dictionary with two keys "name" and "description".

Normally I would expect that you could receive multiple dictionaries, not just "en-US" but keys for other languages like French or German or Japanese; you would then pick the one that is most appropriate for your application, and extract the "name" and "description" keys from it.

Upvotes: 1

Related Questions