1

In a table, Leads, there is a column Data 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:

{  
   "RequestTypeID":1
}

RequestTypeID is a string.

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

EDIT:

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: RequestTypeID.GetDisplayName(); but .GetDisplayName() is not recognized by LINQ.

5
  • You can use JSON.Net to parse the Data field to get the property. But the query would need to be realized first as linq to sql will kick up a fuss Commented Nov 26, 2016 at 14:46
  • I'm not sure I follow Commented Nov 26, 2016 at 14:48
  • is leads a direct call to the table or is it already in memory Commented Nov 26, 2016 at 14:49
  • It is in memory. Previously, it was populated with a call to the DB to load all records from the Lead table Commented Nov 26, 2016 at 14:52
  • Ok that makes it easier. Commented Nov 26, 2016 at 14:53

1 Answer 1

1

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"]
    });
Sign up to request clarification or add additional context in comments.

11 Comments

I'm getting: An expression tree may not contain a dynamic operation
I have an actual object I could use instead of dynamic. But it's complicated by the fact that RequestTypeID is an enum
getting close! DeserializeObject still wants a type. I tried this, but this isn't it either: DeserializeJsonNet<string>(l.Data)["RequestTypeID"]
C#, NET 4.5, MVC, VS2015 -- hope one of those answers your question. Sure do appreciate your help!
And you have latest version of Json.Net referenced?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.