Reputation:
How can i parse a json string in c# controller
public ActionResult GetAjaxSession(string search)
{
...
}
Variable which containt the json string :
search
The Json string :
[{"id_employe":"35"},{"id_employe":"80"},{"id_employe":"136"},{"id_employe":"140"}]
I want to get all id_employe from the string
Upvotes: 2
Views: 13490
Reputation: 27017
Malior's approach is perfectly fine, it's a typed approach. I'd like to mention an alternative way, using Linq and dynamic:
var jsonText="[{\"id_employe\":\"35\"},{\"id_employe\":\"80\"},"
+"{\"id_employe\":\"136\"},{\"id_employe\":\"140\"}]";
var objects = JsonConvert.DeserializeObject<List<dynamic>>(jsonText);
var values = objects.Select(s=>s.id_employe).ToList();
This will create a list, so values
contains the following elements:
35,80,136,140
Because it is dynamic, you don't need to declare an extra class.
Note that both approaches will throw a JsonReaderException
if there is anything wrong with the JSON string (e.g. missing [
etc.). And if the property name isn't found it can throw a RuntimeBinderException
- so you should use a try ... catch
block.
Upvotes: 0
Reputation: 1341
But parsing would be the right way, to get the right data out of your string. Example with using Newtonsoft.Json:
var objects = JsonConvert.DeserializeObject<List<MyObj>>(jsonText);
With the class:
public class MyObj
{
public string id_employe { get; set; }
}
Upvotes: 4