2

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

2
  • 3
    newtonsoft.com/json Commented Jan 8, 2019 at 16:08
  • You have to parse to an object first before you can retrieve the data, unless you plan to parse this thing by hand. If the idea of having DTOs bothers you, use dynamic. Commented Jan 8, 2019 at 16:19

2 Answers 2

4

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 and big thanks 2 days im trying and searching how to do this, your example unstuck me, you really help me :)
0

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();

Fiddle

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.