0

I am trying to implement a dynamic condition on a JSON Object. After searching for a while, I am not able to find any resources which can meet my needs.

In the below fashion, I am getting the JsonObject dynamic string into jsonObject variable.

   string inputFromAPI = client.GetStringAsync(URL).Result;
   dynamic jsonObject = JValue.Parse(inputFromAPI);

I now have a condition which can change on need basis.For example I can have a condition which says "inputFromAPI.DidWeCharge == true && inputFromAPI.DidWeHold == false"

The above line can change on the fly. Any inputs how to address this will be greatly appreciated.

1
  • LINQ to JSON? Commented Mar 7, 2018 at 22:54

3 Answers 3

1

I can't comment for clarification (don't have the rep yet), but if you need to be able to read the property name because it's changing you can do this. You would have to know the name though.

var JSONobj = JObject.Parse(json);

foreach (JToken child in JSONobj.Children())
{
    var prop = child as JProperty; 
    var propertyName = prop.Name; // this will give you the name of the property
    if (propertyName == "DidWeCharge")
    {

       var value = prop.Value; // Do something here with value?
    }
    if (propertyName == "DidWeHold")
    {
       var value = prop.Value; // Do something here with value?
    }

    var propertyType = prop.Value.Type; // this return the type as a JTokenType enum.
}

I don't know how nested your JSON is, so you may have to traverse further down with another foreach on the child by doing child.Children().

Sign up to request clarification or add additional context in comments.

1 Comment

This helped. Thank you.
0

You can use ExpandoObject:

var expandoObj = JsonConvert.DeserializeObject<ExpandoObject>(jsonObject);

expandoObj.yourProperty

JsonConvert is from Newtonsoft.Json package.

2 Comments

Well, in my case if you notice my property name and the codition itself can be dynamic. I do not have a problem navigating to the values within my JsonObject.
Did you try DynamicExpresso for dynamic conditionals? github.com/davideicardi/DynamicExpresso
0

You may be able to use Jpath:

using Newtonsoft.Json -

....

var json = @"
{
    stuff : [
        {
            value : 1
        },
        { 
            value : 2
        }       
    ]
}";


var token = JToken.Parse(json);

var something = token.SelectTokens("$.stuff[?(@.value == 1)]").ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.