问题描述
我是一个带有rEST API的示例项目..在我的POST方法中,我传递了一个带有url的stringify对象。我的动作参数是object。我想把这个对象数据转换成我班级的另一个对象..我的示例代码如下
newuser是对象
Json
I'm diong a sample project with rEST API.. In my POST method i pass an stringify object with the url. my parameter for the action is object. Ineed to convert this object data to another object of my class .. my Sample code is below
newuser is object
Json
$.ajax({
type: "POST",
url: "values/InsertUserDetails",
dataType: "json",
data: JSON.stringify(newuser),
contentType: "application/json; charset=utf-8",
error: function (error) {
alert("TEST !!!");
}
});
C#代码
C# code
public int InsertUserDetails([FromBody]object datatosave)
{
MdlUser objuser = (MdlUser) (datatosave);
return SettingManager.InsertUserDetails(objuser);
}
推荐答案
C#代码
C# code
public int InsertUserDetails([FromBody]object datatosave)
{
MdlUser objuser = (MdlUser) (datatosave);
return SettingManager.InsertUserDetails(objuser);
}
using Serializer = System.Web.Script.Serialization.JavaScriptSerializer;
// (reference assembly System.Web.Extensions
// ...
string jsArray = @"[1,""false"",false]";
string jsDictionary = @"{""x"": 5}";
Serializer serializer = new Serializer();
object array = serializer.DeserializeObject(jsArray);
object dictionary = serializer.DeserializeObject(jsDictionary);
要了解如何从JSON获取输入字符串,请参阅:
[]。
现在,检查对象数组
和字典
。如果你对它们调用 GetType()
,你会看到一个是 System.Object
的数组,另一个是是对象的字典,x是字符串键。这些对象过于通用,因此您可以尝试将它们解析为某些命名类型。这样,您就可以访问某些命名类型及其成员的实例。让我们重写前面的代码示例是这样的打字方式:
To understand how input strings were obtained from JSON, please see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify[^].
Now, inspect the objects array
and dictionary
. If you call GetType()
on them, you will see that one is an array of System.Object
and another one is a dictionary of objects, and "x" is a string key. Such objects are too generic, so you can try to parse them into some named types. This way, you will be able to access the instances of some named types and their members. Let's rewrite the previous code sample is such "typed" way:
using Serializer = System.Web.Script.Serialization.JavaScriptSerializer;
using IntDictionary = System.Collections.Generic.Dictionary<string, int>;
// ...
string jsArray = @"[1,""false"",false]";
string jsDictionary = @"{""x"": 5}";
Serializer serializer = new Serializer();
object[] typedArray = serializer.Deserialize<object[]>(jsArray);
IntDictionary typedDictionary = serializer.Deserialize<IntDictionary>(jsDictionary);
现在你可以使用明确定义类型的实例 object []
和< cod> IntDictionary并实际访问实例的实例成员 typedArray
和 typedDictionary
。
Now you can use instances of explicitly defined types object[]
and <cod>IntDictionary and actually access the instance members of the instances typedArray
and typedDictionary
.
这篇关于如何将对象类型转换为C#类对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!