dynamic JContainer (JSON.NET) & Iterate over properties at runtime

前端 未结 1 1335
北海茫月
北海茫月 2020-12-06 09:43

I\'m receiving a JSON string in a MVC4/.NET4 WebApi controller action. The action\'s parameter is dynamic because I don\'t know anything on the receiving end ab

相关标签:
1条回答
  • 2020-12-06 10:09

    I think this can be a starting point

    dynamic dynObj = JsonConvert.DeserializeObject("{a:1,b:2}");
    
    //JContainer is the base class
    var jObj = (JObject)dynObj;
    
    foreach (JToken token in jObj.Children())
    {
        if (token is JProperty)
        {
            var prop = token as JProperty;
            Console.WriteLine("{0}={1}", prop.Name, prop.Value);
        }
    }
    

    EDIT

    this also may help you

    var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jObj.ToString());
    
    0 讨论(0)
提交回复
热议问题