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?
有帮助吗?

解决方案

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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top