【问题标题】:Parse JSON into anonymous object[] using JSON.net使用 JSON.net 将 JSON 解析为匿名对象 []
【发布时间】: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 的对象将没有任何属性。 JContainerJObject 或将其用作 dynamic 有什么问题?

标签: c# json json.net json-deserialization


【解决方案1】:

您可以通过示例反序列化,使用这样的匿名类型:

string jsonString = "{name:\"me\",lastname:\"mylastname\"}";
var typeExample = new { name = "", lastname = "",data=new int[]{1,2,3} };
var result=JsonConvert.DeserializeAnonymousType(jsonString,typeExample);
int data1=result.data.Where(x => 1);

Json.Net 中的其他方式是使用这样的动态对象:

dynamic result2=JObject.Parse(jsonString);

【讨论】:

  • "dynamic" 类型是完美的,如果我不想创建 json 的模板: //来自 TFS REST API 动态项目的对象 = JsonConvert.DeserializeObject(jsonProjects); var projectName = projects.value[0].name;
【解决方案2】:

一个稍微不同的用例,其中 JSON 字符串是一个匿名类型的数组,以下将起作用。本质上它只是将匿名类型包装在一个数组中。

string json = "[{\"Type\":\"text/xml\",\"Allowed\":\"true\"},{\"Type\":\"application/pdf\",\"Allowed\":\"true\"},{\"Type\":\"text/plain\",\"Allowed\":\"true\"}]";
JsonConvert.DeserializeAnonymousType(json, new[] { new { Type = "", Allowed = true } });

这会导致Linqpad 显示的以下结果。

【讨论】:

    【解决方案3】:
    string jsonString = "{ "Thing":"Thing","That":{"Item1":15,"Item2":"Moo","Item3":{"Count":27,"Type":"Frog"}}}"
    
    Object[] data = JsonConvert.DeserializeObject<Object>(jsonString);
    
    ?
    

    【讨论】:

      【解决方案4】:
      JObject.Parse(jsonString).ToObject<MyType>()
      

      ?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-28
        • 1970-01-01
        相关资源
        最近更新 更多