Question

I am using newtonsoft to serialize and deserialize objects. I am using the following bit of code to read a string from the posted values:

string className;
JToken classToken;
jsonData.TryGetValue("Class", out classToken);
className= (string)classToken;

This works fine. Suppose the following is the JSON that is being posted, how can I read the "Students" array with the above method?

"Students": ["1", "3"],
"Class": "Fifth"

I tried the following code but it gives error 'Can not convert array to string'

string[] StudentsName;
JToken StudentsToken;
jsonData.TryGetValue("Students", out StudentsToken);
StudentsName= (string)StudentsToken;//How to assign this to an array?
Was it helpful?

Solution

Just assign the string to the First Index of the array

string[] StudentsName = new string[5];
JToken StudentsToken;
jsonData.TryGetValue("Students", out StudentsToken);
StudentsName[0] =  StudentsToken.ToString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top