[英]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: 我有一个JavaScript脚本,该脚本进行jQuery AJAX调用,并在“数据”属性中传递了序列化的javascript对象:
data: { Specific: JSON.stringify({DAY: "1", DEP: "2", CARRIER: "3", FLT: "4", LEGCD: "5"})
数据:{特定:JSON.stringify({DAY:“ 1”,DEP:“ 2”,CARRIER:“ 3”,FLT:“ 4”,LEGCD:“ 5”})
It is received in a C# Generic Handler thusly: 因此,它在C#通用处理程序中被接收:
var Specific = JsonConvert.DeserializeObject(context.Request.Params["Specific"]);
In the Generic Handler, within Visual Studio debugger, I can see the received object. 在Visual Studio调试器的通用处理程序中,我可以看到接收到的对象。
Specific = {{ "DAY": "", "DEP": "", "CARRIER": "", "FLT": "", "LEGCD": "" }}
具体= {{“ DAY”:“”,“ DEP”:“”,“ CARRIER”:“”,“ FLT”:“”,“ LEGCD”:“”}}
My question is, how do I reference the received object's properties (DAY, DEP, FLT, etc)? 我的问题是,如何引用接收对象的属性(DAY,DEP,FLT等)?
I tried Specific.DAY
, and Specific["DAY"]
, with no success. 我尝试了
Specific.DAY
和Specific["DAY"]
,但没有成功。
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: 最后以“ Specific”为类型的
System.Object
结束,可能有助于反序列化为自定义类型,如下所示:
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
) 从那里,您应该可以使用典型的点操作(
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: 可以使用更新的C#版本以其他方式完成此反射,如此处的答案之一所述:
How to access property of anonymous type in C#? 如何在C#中访问匿名类型的属性?
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
. 如果JSON中没有
DAY
,则第一个将返回null
,第二个将抛出KeyNotFoundException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.