Parse JSON into anonymous object[] using JSON.net

Ritz picture Ritz · Nov 12, 2013 · Viewed 22.4k times · Source

I have a json string that I want to parse into an object[]:

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

The resulting anonymous object array needs to contain each of the properties of the original json object. My issue is that JsonConvert.DeserializeObject returns a type of JContainer or JObject. I have not been able to identify a way to return a plain vanilla c# object.

This is my current non-functional code from an array of previous attempts. I do not have to use JSON.net but I would like to if possible to ensure compatibility wiith the code generating the json.

JObject deserialized = JsonConvert.DeserializeObject<JObject>(dataString);
object[] data =
deserialized.Children().Where(x => x as JProperty != null).Select(x => x.Value<Object>()).ToArray();

Update

I am using the produced object array to invoke methods via reflection. The types of the parsed json objects are not known at runtime. The problem sticking point is that JObject or JContainer object types do not match the signatures of the methods being invoked. Dynamic has this same side-effect. Methods are being invoked like this:

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

Answer

majimenezp picture majimenezp · Nov 12, 2013

you can deserialize by example, using an anonymous type like this:

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

Other way in Json.Net it's using a dynamic object like this:

dynamic result2=JObject.Parse(jsonString);