0

I have a Json object coming into my WebApi. The structure can take any form. The only thing I know for certain is that somewhere in that structure (could be a top level node, could be a child node) I will have a node made up of:

"data": {
        "mop": "1012346354462",
        "fuelType": "E",
        "Id": "1029dd56-10b1-46cb-9966-3c37e057a470",
        "Status": "SecuredActive",
        "StatusFromDate": "2020-11-20T17:00:00.000Z",
        "ActiveDate": "2020-11-21T00:00:00.000Z",
        "GeneratedReference": "1012346354462_1"
      },

Can anyone help on how I can easily extract this bit of data from the JSon Object. I have a class that maps to these properties, but before I can use it I need to single this out from the rest of the JSON. I'm using C#

bilpor
  • 3,467
  • 6
  • 32
  • 77
  • Assuming your using System.Text.Json: You can use the extensions povided in [this](https://stackoverflow.com/a/61561343/9363973) Q&A to get the `JsonElement` named `data`, and then use [this](https://stackoverflow.com/a/58193164/9363973) Q&A to deserialize it to an object – MindSwipe Apr 13 '21 at 13:51

2 Answers2

1

After much playing around, I've finally found a solution, so thought I'd post in-case others hit a similar issue.

JObject result = JObject.Parse(Request.ToString());

var clientarray = result["events"].Value<JArray>();

var blockIwant = clientarray.Children<JObject>().Select(x => x.Children<JProperty>().Where(y => y.Name == "data").First());
bilpor
  • 3,467
  • 6
  • 32
  • 77
0

use JSON Convert to deserialize the object.

var Data = JsonConvert.DeserializeObject<dynamic>(data);

Then you can access using the Data object. Eg : Console.WriteLine((String)Data.data.fuelTypereturn);

Gives the answer as "E"

Indunil Withana
  • 176
  • 1
  • 8
  • This doesn't work . If my example above is wrapped in another element for example, it errors with `'object' does not contain a definition for 'data'` – bilpor Apr 13 '21 at 15:29