动态 JContainer (JSON.NET) &在运行时迭代属性

2

本文介绍了动态 JContainer (JSON.NET) &在运行时迭代属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在 MVC4/.NET4 WebApi 控制器操作中收到一个 JSON 字符串.该操作的参数是 dynamic,因为我对接收端收到的 JSON 对象一无所知.

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 about the JSON object I'm receiving.

 public dynamic Post(dynamic myobject)        

自动解析 JSON,生成的 dynamic 对象是 Newtonsoft.Json.Linq.JContainer.正如预期的那样,我可以在运行时评估属性,因此如果 JSON 包含类似 myobject.myproperty 的内容,那么我现在可以获取接收到的动态对象并在 C# 代码中调用 myobject.myproperty.到目前为止一切顺利.

The JSON is automatically parsed and the resulting dynamic object is a Newtonsoft.Json.Linq.JContainer. I can, as expected, evaluate properties at runtime, so if the JSON contained something like myobject.myproperty then I can now take the dynamic object received and call myobject.myproperty within the C# code. So far so good.

现在我想遍历作为 JSON 的一部分提供的所有属性,包括嵌套属性.但是,如果我这样做 myobject.GetType().GetProperties() 它只返回 Newtonsoft.Json.Linq.JContainer 的属性,而不是我正在寻找的属性(是 JSON 的一部分).

Now I want to iterate over all properties that were supplied as part of the JSON, including nested properties. However, if I do myobject.GetType().GetProperties() it only returns properties of Newtonsoft.Json.Linq.JContainer instead of the properties I'm looking for (that were part of the JSON).

知道怎么做吗?

推荐答案

我认为这可以作为一个起点

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);
    }
}

编辑

这也可以帮助你

var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jObj.ToString());

这篇关于动态 JContainer (JSON.NET) &amp;在运行时迭代属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14