0

I've tried some examples on here but am tearing my hair out.

I do a query and it returns JSON, inside the JSON are lots of hashes, eg.

{ "gjwiegjeigj": { ....}, "gjeeigjwoeigj": {...} ... }

I want to loop through each of these, and deserialize the contents into an object.

I've created the object, myObject which has all the fields, but I am stuck on deserialising.

I can deserialise straight from the base object using JsonConvert.DeserializeObject but I can't do that, I need to loop through and do that to the children.

I want an array of my custom objects with all the fields taken from the Json as a result of this, I don't care about the title of each one (the garbage hash).

Any ideas? I know I can loop through, which gives me lots of JTokens but that's where I get stuck.

Steve Konves
  • 2,648
  • 3
  • 25
  • 44
NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • 1
    What did you not like [here](http://stackoverflow.com/a/16339492/1906557)? – I4V May 02 '13 at 14:40
  • That question was about .NET 4.5 JSON rather than JSON.NET, but the key issue I am having is that I don't know the name of the field I am deserialising. I can't do ["People"] because the field is called "gjwiegjoawigj" some random name. – NibblyPig May 02 '13 at 14:41
  • What have you tried? Show us some real code and tell us exactly what the real problem is. – ashes999 May 02 '13 at 15:06
  • I'm going to ask a new question since I have it half figured out – NibblyPig May 02 '13 at 15:16

2 Answers2

0

Edit: Reading your question again, you mention both knowing and not knowing all the fields. It sounds like you really don't know exactly what fields the JSON string will contain.

For cases like this, I suggest you use dynamic -- this is where it shines. If you do know all the field names, your class should be deserializing without any issue.

What have you tried? Show us some real code, and real exceptions or problems.

To deserialize into a list of dynamic objects is simple:

dynamic toReturn = JsonConvert.DeserializeObject<List<dynamic>>(rawJson);

You should get back a list of dynamic objects. You can poke it for the fields you want:

Console.WriteLine(toReturn.First().gjwiegjeigj);

ashes999
  • 9,925
  • 16
  • 73
  • 124
0

So I figured it out, basically to get from a collection JTokens which is what I get when I iterate through .Children() on my JSON object, I can either cast it to a JProperty and do .Name to get the name or .Value to get the value, or I can deserialize directly into an object, essentially like this:

MyObject record = (MyObject)JsonConvert.DeserializeObject(myRow.Children().First().ToString(), typeof(MyObject), settings);

Then I don't know need to know the name of the property I am deserializing.

NibblyPig
  • 51,118
  • 72
  • 200
  • 356