❔ Is there a way to access a prop with the help of a string.
Is there a way to access a prop with the help of a string. Like you do in JS like this
myObject["propName"];
?9 Replies
a external app is returning props with first nested level being the ids as propnames. I have the ids in string already available. I want to be able to automatically access them.
dto be looking like this for example
And I want to just map away from the Id so my frontend dont need to know about it but still automatically access by iterating through several of these objects. Which will be possible if I just map the level with id away. Which I will be able to if I just can access it like the question asks for
So if it was js syntax I would just access it like
want to do achieve same result in c# now
If you have the class structure then why do you want to access properties dynamically?
because I dont want the same structure in the frontend
Reasons: I dont want frontend to see the ids, and I dont want to manually change dtos as soon as I add something to the array, or remove.
I'm too tired to think about whether that's a good idea. Anyway, you can use reflection and do
yourObject.GetType().GetProperty("PropName").GetValue(yourObject)
.The bad idea is that the API is returning the dtos like this. But its out of my reach to change it since its 3rd party 🙂
ooh GetValue... forgot that last step
been trying GetProperty()
GetProperty
just returns an object representing the property itself, not bound to any object.was not getting the intellisense for that one
ah never mind this API is making me f'd anyway due to
response.Content.ReadAsAsync<DtoNeededHereAsWell>()
Unless I try to be cleaver with the json while its serialized as string. 🤢
So still have to edit Dto as soon as expected ids changeYe I guess Newtonsofts JObjects is the way to go. and later serialize it. Or automap. not sure what I get yet
https://stackoverflow.com/questions/16459155/how-to-access-json-object-in-c-sharp
Stack Overflow
how to access JSON object in C#
I receive the following Json through a web service:
{
report: {
Id: "aaakkj98898983"
}
}
I want to get value of the Id. How to do this in C#?
THANKS
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.