Reputation: 97
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":"[email protected]",
"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);
Upvotes: 0
Views: 488
Reputation: 5763
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.
Upvotes: 1