❔ Get value out of deserialized json object.
I need to get value out of meta, from the "object".
As for now I also use this:
Dictionary<string, object> msg = (Dictionary<string, object>)result;
But since its generic Im not sure how to access the field value. Any help?
These dont work:
var result = data["meta"]["object"].Value<string>();
var result = data.SelectToken("meta.object").ToString();
var result = data.Descendants()
.OfType<JProperty>()
.FirstOrDefault(x => x.Name == "object")
?.Value;
And here is the json:
10 Replies
Ero#1111
REPL Result: Success
Result: string
Compile: 624.654ms | Execution: 91.993ms | React with ❌ to remove this embed.
yay
Hi,
there are several ways you can go about this.
System.Text.Json
can be used if you want to deserialize it into a strongly typed class, but that requires you to create the class for it first. Luckily there are tools to help convert json to .cs
objects. This can probably be a bit bloated if you worry about that, but it'll be consise and very readable and generally is the preferred way if the payload won't change.
Another approach is to use the more generic JsonElement
(also from STJ) I think they're called, where you instead deserialize this into something more generic where you can access it like you would a dictionary.
I prefer @Eros approach here, that solution is how I'd do it tooYes, it might vary depending on the request thats why it is generic. Im looking trough the other solution that have been posted here
How may it vary? May the content of the json change, or just the values of the contents? Because if you can keep a strongly typed class I'd prefer that
the content of
object
changes types depending on the request, then it's difficult
if you know the type beforehand, because you know what it returns based on the request, a generic parameter might workgot another solution
string meta = (new JavaScriptSerializer()).Serialize(msg["meta"]);
string obj = meta.Substring(meta.IndexOf("object")+9);
1. Generate classes from this JSON
2. Deserialize to those classes
3. Hurray, now you're using the benefits of C#'s type system in full and you can get rid of magic strings!
+9?
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.