user1418704 user1418704 - 8 months ago 53
C# Question

LINQ need to parse JSON out of a column

In a table, Leads, there is a column

that contains a JSON string. In a LINQ statement, I need to extract a field from that JSON:

var results = from l in leads
select new MyLeadObject
LeadID = l.LeadID,
RequestType = (string)l.Data["RequestTypeID"]

Here's a shortened version of the JSON:


is a string.

I've been reading other threads and trying to cobble this together. Not having much luck.


With help from Nkosi, I got this far:

RequestType = (string)JSONNetSerialization.DeserializeJsonNet<LeadData>(l.Data).RequestTypeID

The only problem is that LeadData.RequestTypeID is an enum, so it won't convert the enum to a string. I'm not sure how to get the value of the enum instead of the entire enum itself. Outside of LINQ I could do this:
is not recognized by LINQ.

Answer Source

You can use Json.Net to parse the JSON in Data field to get the property.

var results = leads.Select(l =>
    new MyLeadObject {
        LeadID = l.LeadID,
        RequestType = (string)JsonConvert.DeserializeObject(l.Data)["RequestTypeID"]