Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON into anonymous object[] using JSON.net

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);
like image 627
Ritz Avatar asked Nov 11 '13 23:11

Ritz


People also ask

How do I deserialize JSON to an object?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is JSON parse in C#?

Introduction to JSON Parser in C# JSON (JavaScript Object Notation) parse is language-independent which is a lightweight data-interchanging format, self-describing, and easy to understand. JSON parser is an alternative to XML it represents objects in structural text format and the data stored in key-value pairs.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


3 Answers

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);
like image 172
majimenezp Avatar answered Sep 26 '22 21:09

majimenezp


A slightly different use case in which the JSON string is an array of anonymous types the following will work. Essentially it just wraps the anonymous types within an array.

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

This results in the following as visualized by Linqpad.

enter image description here

like image 22
Tedford Avatar answered Sep 22 '22 21:09

Tedford


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

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

?
like image 44
SJP Avatar answered Sep 23 '22 21:09

SJP