anon
anon

Reputation:

Parsing/Iterating over Json

I'm fairly new to parsing Json with C# and i'm having a little issue i can't work my head around.

My data looks something like this:

{
    "languages": {
        "ja_lang": {
            "data": {
                "name": "Japanese"
            },
            "files": [["ja",
            "Japanese File",
            "lang_ja.txt"]]
        },
        "en_lang": {
            "data": {
                "name": "English"
            },
            "files": [["en",
            "English File",
            "lang_en.txt"]]
        }
    }
}

Now i want to iterate over the items in languages and only work with the one where the object-name starts with "ja_" (in this case it would only work with "ja_lang" and ignore "en_lang"), then extract the name inside data and the "lang_ja.txt" in files.

To Parse the Json in C# i downloaded the Newtonsoft.Json library and came up with this:

dynamic json_obj = JsonConvert.DeserializeObject("json string");

// when debugging language holds { "ja_lang": { "data": { "name": "Japanese" }, "files": [["ja", "Japanese File", "lang_ja.txt"]] } }
foreach (var language in json_obj.languages)
{
    // not sure how i can access the object-name
    /*if(!language.StartsWith("ja_"))
        continue;*/

    // Exception: 'Newtonsoft.Json.Linq.JProperty' does not contain a definition for 'data' - Not sure why it is treated as a property?
    var name = language.data.name;
    var file = language.files[2];
}

I'm sorry for this probably dumb question, but i've been trying to cast it to different types and searched the web for solutions, but i just couldn't figure it out. So if someone could help me out with this i would be really greatful.

Thanks in advance!

Upvotes: 0

Views: 97

Answers (2)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391306

Since you're stating in a comment (on an answer that has been deleted) that the data changes so a fixed model won't work, you can still fix what is known:

Here's a LINQPad program that demonstrates:

void Main()
{
    var collection = JsonConvert.DeserializeObject<LanguagesCollection>(File.ReadAllText(@"c:\temp\test.json"));
    foreach (var keyValuePair in collection.Languages)
        if (keyValuePair.Key.StartsWith("ja_"))
            keyValuePair.Value.Dump();

}

public class LanguagesCollection
{
    public Dictionary<string, JObject> Languages { get; } = new Dictionary<string, JObject>();
}

This will deserialize the outer object, with the "languages" key, and inside you have a dictionary with the keys, "ja_lang", "en_lang", and you can just process the values as you see fit. These are left as JObject which means they will contain whatever json was present as a value for that key in the dictionary.

Upvotes: 3

Amelia B
Amelia B

Reputation: 1084

Using a site like json2sharp you can just pass your json data in and get a ready to use c# model out.

Then you can easily deserialize your json data into that c# model and use the properties for much easier handling:

            string jsonData = @"{
                                'languages': {
                                    'ja_lang': {
                                        'data': {
                                            'name': 'Japanese'
                                        },
                                        'files': [['ja',
                                        'Japanese File',
                                        'lang_ja.txt']]
                                    },
                                    'en_lang': {
                                        'data': {
                                            'name': 'English'
                                        },
                                        'files': [['en',
                                        'English File',
                                        'lang_en.txt']]
                                    }
                                }
                            }";

        RootObject data = JsonConvert.DeserializeObject<RootObject>(jsonData);


        foreach(Languages lang in data.languages) //would work if Languages was a listing
        {

        }

Although I admit that your Json is a bit strange and that Languages most likly should be a listing and not a property for each language.

Upvotes: 0

Related Questions