Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get property from dynamic JObject programmatically

Tags:

I'm parsing a JSON string using the NewtonSoft JObject. How can I get values from a dynamic object programmatically? I want to simplify the code to not repeat myself for every object.

public ExampleObject GetExampleObject(string jsonString) { ExampleObject returnObject = new ExampleObject(); dynamic dynamicResult = JObject.Parse(jsonString); if (!ReferenceEquals(dynamicResult.album, null))    {        //code block to extract to another method if possible        returnObject.Id = dynamicResult.album.id;         returnObject.Name = dynamicResult.album.name;        returnObject.Description = dynamicResult.albumsdescription;        //etc..    } else if(!ReferenceEquals(dynamicResult.photo, null))    {        //duplicated here        returnObject.Id = dynamicResult.photo.id;        returnObject.Name = dynamicResult.photo.name;        returnObject.Description = dynamicResult.photo.description;        //etc..    } else if.. //etc..  return returnObject; } 

Is there any way I can extract the code blocks in the "if" statements to a separate method e.g:

private void ExampleObject GetExampleObject([string of desired type goes here? album/photo/etc]) {   ExampleObject returnObject = new ExampleObject();   returnObject.Id = dynamicResult.[something goes here?].id;   returnObject.Name = dynamicResult.[something goes here?].name;   //etc..   return returnObject; } 

Is it even possible since we can't use reflection for dynamic objects. Or am I even using the JObject correctly?

Thanks.

like image 265
dcdroid Avatar asked Apr 19 '13 05:04

dcdroid


2 Answers

Assuming you're using the Newtonsoft.Json.Linq.JObject, you don't need to use dynamic. The JObject class can take a string indexer, just like a dictionary:

JObject myResult = GetMyResult(); returnObject.Id = myResult["string here"]["id"]; 

Hope this helps!

like image 84
Connie Hilarides Avatar answered Sep 19 '22 21:09

Connie Hilarides


Another way of targeting this is by using SelectToken (Assuming that you're using Newtonsoft.Json):

JObject json = GetResponse(); var name = json.SelectToken("items[0].name"); 

For a full documentation: https://www.newtonsoft.com/json/help/html/SelectToken.htm

like image 40
Ziad Akiki Avatar answered Sep 17 '22 21:09

Ziad Akiki