Search code examples
c#jsonparser

get the value of JSON parameter c#


I'm trying to get the id parameter from the json below without success, using c#. It's a double array (users/warings)

JSON:
contents = "{\"users\":[{\"id\":64,\"username\":\"100146\",\"firstname\":\"NAME\",\"lastname\":\"LASTNAME PROFILI\",\"department\":\"\",\"firstaccess\":0,\"lastaccess\":0"}],\"warnings\":[]}"

this is what I tried

JavaScriptSerializer serializer = new JavaScriptSerializer();
object obj1 = serializer.DeserializeObject(contents);
object obj2 = obj1["users"];
string id = obj2["id"];

I get an error in obj2. I don't want to create a class to parse the JSON into, just extract the id value from the 'users' array is enough

thanks for your time!


Solution

  • Try using Newtwonsoft for this:

    var json = "{\"users\":[{\"id\":64,\"username\":\"100146\",\"firstname\":\"NAME\",\"lastname\":\"LASTNAME PROFILI\",\"department\":\"\",\"firstaccess\":0,\"lastaccess\":0}],\"warnings\":[]}";
    
    dynamic data = JObject.Parse(json);
    
    var id = data.users[0].id;