I'm trying to list the following array from a json file into items in my combobox.
{
"label_selection" : ["Label A","Label B","Label C","Label D","Label E","Label F"]
}
Here is my Class:
namespace namespace1 {
[Serializable]
public class Labels {
public string label_selection { get; set; }
}
public class RootObject {
public List<Labels> label_selection { get; set; }
}
}
And here is my function:
private void LoadComboItems() {
string path = @"labelselection/labels.json";
var str = File.ReadAllText(path);
var x = JsonConvert.DeserializeObject<RootObject>(str);
foreach (var element in x.label_selection) {
label_combobox.Items.Add(element.ToString());
}
}
I'm getting an error that says:
Newtonsoft.Json.JsonSerializationException HResult=0x80131500 Message=Error converting value "Label A" to type 'namespace1.Labels'. Path 'label_selection[0]', line 2, position 30. Source=Newtonsoft.Json
Inner Exception 1: ArgumentException: Could not cast or convert from System.String to namespace1.Labels.
The error occurs at: var x = JsonConvert.DeserializeObject(str);
Can somebody help me with this error? I'm very new to C#. Thank you in advance.
CodePudding user response:
The shown json is an object with a property label_selection that is a collection of strings. label_selection
property is not a collection of
Labels
objects.
I think this should work:
public class RootObject {
public List<string> label_selection { get; set; } // Change 1. List of strings
}
(...)
var x = JsonConvert.DeserializeObject<RootObject>(str);
foreach (var element in x.label_selection)
{
label_combobox.Items.Add(element); // Change 2. No .ToString()
}
CodePudding user response:
Cannot cast System.String to namespace1.Labels.
What is element <label_combobox> ? May be it's not Label.
Try crate new Label, and add to label_combobox.
Maybe like this code.
Labels= new Labels();
label1.label_selection= element.ToString();
label_combobox.Items.Add(label1);