Dominik Lemberger
Dominik Lemberger

Reputation: 2426

Convert JSON [][] to object in c#

I have a little problem converting my JSON Object I have to something I can work within C# code.

     { "CheckboxHours": { 
           "method": "ID", 
           "valueparts": [ 
                 "Hour", 
                 [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" ] 
]
        }
     }

This is my JSON String I have, which is for creates me the Selenium Object. What i want is to combine the values from valueparts[0] ("Hour") with valueparts[1][0-23] with each other and create an array of Selenium Objects

var jsonData = JsonConvert.DeserializeObject<jsonc#file>(_jsonFile);
Object[] hours = (Object[])jsonData.CheckboxHours.Valueparts[1];
SeleniumCheckBox[] checkbox = new SeleniumCheckBox[hours.Length];
for (int i = 0; i < hours.Length; ++i)
{
                cbHour[i] = new SeleniumCheckBox(jsonData.CheckboxHours.Valueparts[0].ToString() + hours[i]);
}

The SeleniumCheckBox is a Class I made which just takes the value and creates in the background a new Selenium Element with findElement(By.ID(value)). This is working already.

My Problem here is that he doesn't allow the Conversion from jsonData to Object[] and I don't really know how I can handle this.

I hope it is clear what I want to have - if not feel free to ask for more specific data.

Upvotes: 0

Views: 254

Answers (2)

Turgut Kanceltik
Turgut Kanceltik

Reputation: 639

I think. You can try this.

var jsonData = JsonConvert.DeserializeObject<dynamic>(_jsonFile);
var hours = jsonData.CheckboxHours.valueparts[1];
foreach (var hour in hours)
{
    //Some code
}

Upvotes: 1

Martin
Martin

Reputation: 1

I am not sure if I understood everything correctly, but the reason for failure in deserialization might be that valueparts is List parameter, usually in c# the Lists contain only 1 type of parameters eg. string, or int. In your case, "Hour" (valueparts[0]) is a string, and valueparts[1] is List. I assume here is the conflict with deserializing the JSON string.

{
 CheckboxHours:{
     "method":"ID",
     "valueparts":{
        Measure: "Hour",
        MesureValues: 
        [
          "0","1","2","3","4","5","6","7",
          "8","9","10","11","12","13","14",
          "15","16","17","18","19","20",
          "21","22","23"
        ]
      }
   }
}

Change valueparts to object, as in the code above, so you can use Hour as string and the values as List.

Upvotes: 0

Related Questions