KWallace
KWallace

Reputation: 1700

How to reference deserialized object properties received from javascript in C# generic handler?

I have a JavaScript script that makes a jQuery AJAX call, and passes a serialized javascript object in the "data" property:

data: { Specific: JSON.stringify({DAY: "1", DEP: "2", CARRIER: "3", FLT: "4", LEGCD: "5"})

It is received in a C# Generic Handler thusly:

var Specific = JsonConvert.DeserializeObject(context.Request.Params["Specific"]);

In the Generic Handler, within Visual Studio debugger, I can see the received object.

Specific = {{ "DAY": "", "DEP": "", "CARRIER": "", "FLT": "", "LEGCD": "" }}

My question is, how do I reference the received object's properties (DAY, DEP, FLT, etc)?

I tried Specific.DAY, and Specific["DAY"], with no success.

Upvotes: 0

Views: 267

Answers (2)

Matthew D
Matthew D

Reputation: 196

Rather than using

var Specific = JsonConvert.DeserializeObject(context.Request.Params["SpecificFlt"]);

And ending up with a type of System.Object for "Specific", It might help to deserialize to a custom type as follows:

public class SpecificObj
{
    public string DAY {get; set;}
    public string DEP {get; set;}
    public string CARRIER {get; set;}
    public string FLT {get; set;}
    public string LEGCD {get; set;}
}

And

var Specific = JsonConvert.DeserializeObject<SpecificObj>(context.Request.Params["SpecificFlt"]);

From there you should be able to access the properties using the typical dot operation (Specific.DAY)

EDIT: Alternatively you can use reflection:

Type t = Specific.GetType();
PropertyInfo p = t.GetProperty("DAY");
string day = (string)p.GetValue(Specific);

This reflection can be done other ways using newer versions of C# as detailed in one of the answers here:

How to access property of anonymous type in C#?

Upvotes: 1

Rafał Rutkowski
Rafał Rutkowski

Reputation: 1449

If you don't want to create the class, the following will also work

var specific = JObject.Parse(json);
// specific["DAY"] alone will return a JToken (JValue in this case),
// so use the explicit conversion to string
var day = (string)specific["DAY"];

or, if all the values are strings

var specific = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
var day = specific["DAY"]

If DAY is not present in the JSON, the first one will return null, the second one will throw KeyNotFoundException.

Upvotes: 0

Related Questions