0

I'm looking at the feasibility of creating a dynamic JSON service within my app that will link to outlying JSON services and pull in similar data (but it will have different names). That way, I won't have to create a JSON object / mapping for the 1000's of services that this will be connecting to. My thoughts are to create a mapping between the different JSON services and mine using a configuration created with in the app.

I'm able to create a dynamic JSON object from JSON data using this:

    private static void Deserialize(string szJsonData)
    {
        dynamic dObj = JObject.Parse(szJsonData);
    }

But to access data within that dynamic object, it appears I still need to know the name and access it like this:

string name = dObj.name;

What would make this feasible is if I could do something like this:

string nameMapping = "name";
string name = dObj[nameMapping];

Which would allow me to configure a dynamic mapping back to data within my app.

How could this be accomplished?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Zonus
  • 2,313
  • 2
  • 26
  • 48
  • you can map the object with de `propertyReflection` check the properties names of the object, and compare with nameMapping it could work – Black Hole Apr 04 '19 at 18:15
  • If using BSON isn't any issue, you can also parse strings to `BsonDocument` and run through its elements like a dictionary and can even use the notation `dObj[nameMapping]` as you specified. `MongoDB.Bson` is a good library for such. – Aman Agnihotri Apr 04 '19 at 18:23
  • 3
    Don't assign your `JObject` to a `dynamic` variable. `JObject` already supports the syntax you want. `JObject jObj = JObject.Parse(szJsonData); string name = jObj["name"];` – Brian Rogers Apr 04 '19 at 19:00
  • Oh wow! You are right! That works! THANKS! – Zonus Apr 04 '19 at 20:57
  • So duplicate of [How to get property from dynamic JObject programmatically](https://stackoverflow.com/q/16097768/3744182) then? – dbc Apr 05 '19 at 05:11

0 Answers0