【发布时间】:2013-11-23 22:40:58
【问题描述】:
我有一个 json 字符串,我想解析成一个对象[]:
{ "Thing":"Thing","That":{"Item1":15,"Item2":"Moo","Item3":{"Count":27,"Type":"Frog"}}}
生成的匿名对象数组需要包含原始 json 对象的每个属性。我的问题是 JsonConvert.DeserializeObject 返回一种 JContainer 或 JObject。我无法确定返回普通 c# 对象的方法。
这是我以前尝试的数组中的当前非功能代码。我不必使用 JSON.net,但如果可能的话,我想确保与生成 json 的代码兼容。
JObject deserialized = JsonConvert.DeserializeObject<JObject>(dataString);
object[] data =
deserialized.Children().Where(x => x as JProperty != null).Select(x => x.Value<Object>()).ToArray();
更新
我正在使用生成的对象数组通过反射调用方法。解析的 json 对象的类型在运行时是未知的。问题的症结在于 JObject 或 JContainer 对象类型与被调用方法的签名不匹配。动态具有同样的副作用。方法被这样调用:
Type _executionType = typeof(CommandExecutionDummy);
CommandExecutionDummy provider = new CommandExecutionDummy();
var method = _executionType.GetMethod(model.Command,
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
if (method == null)
throw new InvalidCommandException(String.Format("Invalid Command - A command with a name of {0} could not be found", model.Command));
return method.Invoke(provider, model.CommandData);
【问题讨论】:
-
你想完成什么?
-
运行时类型为
Object的对象将没有任何属性。JContainer或JObject或将其用作dynamic有什么问题?
标签: c# json json.net json-deserialization