0

I have JSON object, something like this, and its dynamic, jsonInput=

{
    "CONTRATE":80,
    "SALINC":30,
    "RETAGE":67,
    "MARSTATUS":"single",
    "SPOUSEDOB":"1970-01-01",
    "VIEWOPTION":"pension"
}

I am converting it into .NET dynamic object using Newtonsoft.Json converter:

var jsonDynamic = JsonConvert.DeserializeObject<dynamic>(jsonInput);

Now I have dynamic jsonDynamic .NET object.

How can I get it's properties now? These should be jsonDynamic.CONTRATE, jsonDynamic.SALINC etc...

How can I get the names of these properties from jsonDynamic?

Thanks.

monstro
  • 6,254
  • 10
  • 65
  • 111
  • I personally used the WrapObject method from here to be able to do what you describe. It is internal so I couldn't access it directly. https://github.com/jbogard/aspnetwebstack/blob/master/src/System.Web.Helpers/Json.cs – jones6 Apr 02 '15 at 21:15
  • You don't need to use `dynamic` here. It is a `JObject` and you can use it mostly like a dictionary. Look at the documentation for it. – Jeff Mercado Apr 02 '15 at 22:32

3 Answers3

1
var jobj = JObject.Parse(jsonInput);
dynamic jsonDynamic = jobj;

var dict = jobj.Children()
               .OfType<JProperty>()
               .ToDictionary(x => x.Name, x => x.Value);

int c = (int)dict["CONTRATE"];

or if you want only property names

var propNames = jobj.Children()
                    .OfType<JProperty>()
                    .Select(x => x.Name)
                    .ToList();
EZI
  • 15,209
  • 2
  • 27
  • 33
0

You could create a class that would represent the json you want to deserialize, like below:

public class ClassName
{
    public int Contrate { get; set; }
    public int Salinc { get; set; }
    // Here you will place the rest of your properties.
}

and then just use this:

var jsonDynamic = JsonConvert.DeserializeObject<ClassName>(jsonInput);

This way you will avoid making use of a dynamic object.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • Thats the point ) I can't. The structure of JSON object is generated in runtime, its unknown. – monstro Apr 02 '15 at 23:12
  • @Donwvoter I would appreciate If you could point out waht's wrong with this answer. If it is totally wrong, I will remover it. Otherwise, I will correct my mistake. Thank you in advance. – Christos Jun 15 '16 at 19:07
-1

You should deserialize into a Dictionary and then you can loop through the Keys to get the property names

Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonInput);

You can access the values.Keys to get the property names then.

Praveen Paulose
  • 5,741
  • 1
  • 15
  • 19
  • I need to deserialize it into an object, since I have to pass that object down the pipeline to WCF service. So it has to be dynamic not generic T. but, maybe u'r right, for the purpose of getting it's properties, I could probably do that (if it works) – monstro Apr 02 '15 at 23:14