0

I am trying to deserialize an object that an API sends me, but when doing so I cannot extract the values.

My object as JSON looks like this:

{
   "Obj":
    {
        "id":19,
        "name":"test",
        "email":"test@mail.com",
        "password":"0439434dae91c10c3bc073af1e76addf8f57a30ce0a7de0438b3aaad34b85200d41d01078f2ee786b3130b4ed4e39e3e26090da5d9f87420454dfdd182761cce",
        "city":"Texas",
        "age":37,
        "date":"2022-05-09T00:00:00",
        "mp":0,
        "du":0,
        "active":false,
        "userid":0,
            "user":""
    },
   "message":null,
   "error":false,
   "information":
    {
       "menssages":"Ok, Results",
       "error":false,
       "success":true,
       "userId":0,
           "user":"",
           "register":0,
       "pages":0
    }
}

My code:

    result = GetWebRequest("api/ClientId/" + id);
    object rest = new JavaScriptSerializer().DeserializeObject(result.ToString());
    
    Dictionary<string, object> keys = (Dictionary<string, object>)((object)rest);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

I'd suggest using JSON.Net for both performance as well as features.

var account = JsonConvert.DeserializeObject<Account>(jsonString);

If you're using ASP.NET Core (not quite clear from your question/tags), you can also use the built-in System.Text.Json:

var weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(jsonString);

Both approaches are much cleaner as you're working with classes instead of a Dictionary. Not that a Dictionary is wrong in any sense, this is just not an optimal use case for it, in particular because you're dealing with nested instances. Though in general, typed access to the properties of your data is almost always a preferred solution.

J.P.
  • 5,567
  • 3
  • 25
  • 39
  • With the JsonConvert it brings me an object, but to get the value of the "id" , i have to do the following: `((Newtonsoft.Json.Linq.JValue)((Newtonsoft.Json.Linq.JProperty)((Newtonsoft.Json.Linq.JContainer)prueba.Objeto).First).Value).Value;` , is there any way to make it shorter? – Jorge Rojas C. May 26 '22 at 17:45
  • Yeah, that shouldn't be necessary. What does the class you're casting to look like? If that has an `Id` property of type integer, JSON.Net should be able to convert it with ease. – J.P. May 26 '22 at 20:45