使用JSON.net将JSON解析为匿名对象[]

时间:2013-11-11 23:29:03

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

我有一个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);

4 个答案:

答案 0 :(得分:18)

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

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

答案 1 :(得分:5)

稍微不同的用例,其中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可视化。

enter image description here

答案 2 :(得分:1)

string jsonString = "{ "Thing":"Thing","That":{"Item1":15,"Item2":"Moo","Item3":{"Count":27,"Type":"Frog"}}}"

Object[] data = JsonConvert.DeserializeObject<Object>(jsonString);

?

答案 3 :(得分:-1)

JObject.Parse(jsonString).ToObject<MyType>()