Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to deserailise JSON Object in C# Without knowing structure

Is it possible to take a JSON object in C# that I read from from another source and convert the contents to files. The problem is I don’t know the structure of the incoming objects.

So far I’ve got this:

 var response = await client.GetAsync("https://blahblah/creds" +
     "?ApiKey=" + textBox_password.Text +
     "&deviceId=" + deviceId +
     "&modelNum=" + modelNum);

 var res = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
 var resJson = JsonConvert.DeserializeObject(res);
 this.textBox_Stream.AppendText("responseBody = " + resJson + "\r\n"); 

Which gives me:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

responseBody = {
  "statusCode": 200,
  "body": {
    "modelNum": "42",
    "creds": "[{\"deviceid.txt\":\"4DA23E\",\"pac.txt\":\"580795498743\"}]",
    "deviceId": "4DA23E"
  }
}

What I want to do is create a folder called 4DA23E and place one file inside it for each entry in the creds object.

device.txt will contain 4DA23E
pac.tct will contain 580795498743

etc. I can’t figure out a dynamic way to extract the stuff I need. Goes without saying, I am not a C# programmer! So, please be kind.

>Solution :

Don’t use JsonConvert.DeserializeObject. That’s best when you know the schema of the JSON object and you’ve made a corresponding C# model.

First, parse the outer response JSON

var res = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
JObject resJson = JObject.Parse(res);

Now pull out the value of the "creds" property and re-parse it.

var credsJsonRaw = resJson["body"]["creds"].Value<string>();
JArray credsJson = JArray.Parse(credsJsonRaw);

Now you can loop through each object in the array, and each property in each object.

foreach (JObject obj in credsJson)
{
    foreach (JProperty prop in obj.Properties)
    {
        Console.WriteLine($"Name = {prop.Name}");
        Console.WriteLine($"Value = {prop.Value.Value<string>()}");
    }
}

For your example, this prints

Name = deviceid.txt
Value = 4DA23E
Name = pac.txt
Value = 580795498743
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading