hasan demirtaƟ hasan demirtaƟ - 3 years ago 207
JSON Question

C# and json data parsing

I have a problem on data parsing, I am using C# in Visual Studios and I need a parsing algorithm for my json file. This is the structure:

{
"objects": {
"minecraft/sounds/mob/stray/death2.ogg": {
"hash": "d48940aeab2d4068bd157e6810406c882503a813",
"size": 18817
},
"minecraft/sounds/mob/husk/step4.ogg": {
"hash": "70a1c99c314a134027988106a3b61b15389d5f2f",
"size": 9398
},
"minecraft/sounds/entity/rabbit/attack2.ogg": {
"hash": "4b90ff3a9b1486642bc0f15da0045d83a91df82e",
"size


I want to pull "minecraft/sounds/mob/stray/death2.ogg" and "hash" the data.

My C# code:

HttpWebRequest reqobje = WebRequest.Create(assetsurl) as HttpWebRequest;

using (HttpWebResponse response = reqobje.GetResponse() as HttpWebResponse)
{
StreamReader objejsonsr = new StreamReader(objectjson);
jsonVerisi = objejsonsr.ReadToEnd();
}

parser = JObject.Parse(jsonVerisi);
JToken job = parser["objects"];

Answer Source

Since you're using json.net, you can deserialize the string into any object you need. The sample below is an anonymous type with dictionary so you can use the dynamic keys that are coming back:

var result = JsonConvert.DeserializeAnonymousType(jsonVerisi, new { objects =
    new Dictionary<string, Dictionary<string, string>>() });
var objects = result.objects; // key/value;

This is one way you can use it (maybe even to map to your own model instead of anonymous types to make it easier to work with):

var objects = result.objects
    .Select(m => new
    {
        Path = m.Key,
        Hash = m.Value["hash"],
        Size = int.TryParse(m.Value["size"], out var value) ? value : 0,
    }).ToList();
var path = objects[0].Path; // Get the path of the first object
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download