是否有一个简单的方法来填充我的c#对象与JSON对象通过AJAX传递?

这是使用JSON.stringify从页面传递给c# WEBMETHOD的JSON对象

{
    "user": {
        "name": "asdf",
        "teamname": "b",
        "email": "c",
        "players": ["1", "2"]
    }
}

接收JSON对象的c# webmethod

[WebMethod]
public static void SaveTeam(Object user)
{

}

c#类,表示传递给WebMethod的JSON对象的对象结构

public class User
{
    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
    public Array players { get; set; }
}

在c#中使用JSON的一个好方法是使用JSON。网

快速入门和来自JSON的API文档。官方网站帮助你使用它。

下面是如何使用它的例子:

public class User
{
    public User(string json)
    {
        JObject jObject = JObject.Parse(json);
        JToken jUser = jObject["user"];
        name = (string) jUser["name"];
        teamname = (string) jUser["teamname"];
        email = (string) jUser["email"];
        players = jUser["players"].ToArray();
    }

    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
    public Array players { get; set; }
}

// Use
private void Run()
{
    string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
    User user = new User(json);

    Console.WriteLine("Name : " + user.name);
    Console.WriteLine("Teamname : " + user.teamname);
    Console.WriteLine("Email : " + user.email);
    Console.WriteLine("Players:");

    foreach (var player in user.players)
        Console.WriteLine(player);
 }

对于您的代码示例,您应该不需要做任何其他事情。

如果你将JSON字符串传递给你的web方法,它将自动解析JSON字符串并创建一个填充的User对象作为你的SaveTeam方法的参数。

一般来说,你可以使用如下所示的JavascriptSerializer类,或者为了获得更大的灵活性,可以使用任何一个Json框架(Jayrock Json是一个很好的框架)来轻松地操作Json。

 JavaScriptSerializer jss= new JavaScriptSerializer();
 User user = jss.Deserialize<User>(jsonResponse); 

JSON。Net是最好的选择,但是,取决于对象的形状以及是否存在循环依赖关系,你可以使用JavaScriptSerializer或DataContractSerializer。


如果您使用的是。net 3.5或更高版本,为了保持您的选择余地,这里有一个封装好的示例,您可以使用泛型直接从框架中使用。正如其他人所提到的,如果不仅仅是简单的对象,那么就应该使用JSON.net。

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.UTF8.GetString(ms.ToArray());
    return retVal;
}

public static T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    return obj;
}

你需要:

using System.Runtime.Serialization;

using System.Runtime.Serialization.Json;

使用JavaScriptSerializer()比提供的通用解决方案更严格:

public static T Deserialize<T>(string json)

当向服务器传递json时,如果json与您试图转换的Object定义不完全匹配,这可能会很方便。


public static class Utilities
{
    public static T Deserialize<T>(string jsonString)
    {
        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
        {    
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            return (T)serializer.ReadObject(ms);
        }
    }
}

更多信息请访问以下链接 http://ishareidea.blogspot.in/2012/05/json-conversion.html

关于DataContractJsonSerializer类你可以在这里阅读。


codeplex上的JSON c#类生成器生成的类可以很好地与NewtonSoftJS一起工作。


下面的两个例子使用了其中之一

JavaScriptSerializer在System.Web.Script.Serialization或 Json。在System.Web.Helpers下解码


例1:使用System.Web.Script.Serialization

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Script.Serialization;

namespace Tests
{
    [TestClass]
    public class JsonTests
    {
        [TestMethod]
        public void Test()
        {
            var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            dynamic jsonObject = serializer.Deserialize<dynamic>(json);

            dynamic x = jsonObject["user"]; // result is Dictionary<string,object> user with fields name, teamname, email and players with their values
            x = jsonObject["user"]["name"]; // result is asdf
            x = jsonObject["user"]["players"]; // result is object[] players with its values
        }
    }
}

用法:JSON对象到自定义c#对象

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Script.Serialization;
using System.Linq;

namespace Tests
{
    [TestClass]
    public class JsonTests
    {
        [TestMethod]
        public void TestJavaScriptSerializer()
        {
            var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
            User user = new User(json);
            Console.WriteLine("Name : " + user.name);
            Console.WriteLine("Teamname : " + user.teamname);
            Console.WriteLine("Email : " + user.email);
            Console.WriteLine("Players:");
            foreach (var player in user.players)
                Console.WriteLine(player);
        }
    }

    public class User {
        public User(string json) {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var jsonObject = serializer.Deserialize<dynamic>(json);
            name = (string)jsonObject["user"]["name"];
            teamname = (string)jsonObject["user"]["teamname"];
            email = (string)jsonObject["user"]["email"];
            players = jsonObject["user"]["players"];
        }

        public string name { get; set; }
        public string teamname { get; set; }
        public string email { get; set; }
        public Array players { get; set; }
    }
}

例2:使用System.Web.Helpers

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Helpers;

namespace Tests
{
    [TestClass]
    public class JsonTests
    {
        [TestMethod]
        public void TestJsonDecode()
        {
            var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
            dynamic jsonObject = Json.Decode(json);

            dynamic x = jsonObject.user; // result is dynamic json object user with fields name, teamname, email and players with their values
            x = jsonObject.user.name; // result is asdf
            x = jsonObject.user.players; // result is dynamic json array players with its values
        }
    }
}

用法:JSON对象到自定义c#对象

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Helpers;
using System.Linq;

namespace Tests
{
    [TestClass]
    public class JsonTests
    {
        [TestMethod]
        public void TestJsonDecode()
        {
            var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
            User user = new User(json);
            Console.WriteLine("Name : " + user.name);
            Console.WriteLine("Teamname : " + user.teamname);
            Console.WriteLine("Email : " + user.email);
            Console.WriteLine("Players:");
            foreach (var player in user.players)
                Console.WriteLine(player);
        }
    }

    public class User {
        public User(string json) {
            var jsonObject = Json.Decode(json);
            name = (string)jsonObject.user.name;
            teamname = (string)jsonObject.user.teamname;
            email = (string)jsonObject.user.email;
            players = (DynamicJsonArray) jsonObject.user.players;
        }

        public string name { get; set; }
        public string teamname { get; set; }
        public string email { get; set; }
        public Array players { get; set; }
    }
}

这段代码需要添加System.Web.Helpers命名空间,

% ProgramFiles % Microsoft ASP.NET喝ASP。网网络 布林{版本Assemblies喝System.Web.Helpers.dll

Or

% ProgramFiles (x86) % \ Microsoft ASP.NET \ ASP。网网络 页面{VERSION} \总成\ System.Web.Helpers.dll

希望这能有所帮助!


既然我们都喜欢一行代码

Newtonsoft比java脚本序列化器更快。 ... 这个依赖于Newtonsoft的NuGet包,这个包很流行,比默认的序列化器更好。

如果我们有类,那么使用下面。

Mycustomclassname oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<Mycustomclassname>(jsonString);

没有类则使用动态

var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonString);

JavaScript Serializer:需要使用System.Web.Script.Serialization;

public class JavaScriptSerializerDeSerializer<T>
{
    private readonly JavaScriptSerializer serializer;

    public JavaScriptSerializerDeSerializer()
    {
        this.serializer = new JavaScriptSerializer();
    }

    public string Serialize(T t)
    {
        return this.serializer.Serialize(t);
    }

    public T Deseralize(string stringObject)
    {
        return this.serializer.Deserialize<T>(stringObject);
    }
}

数据契约序列化器:需要使用System.Runtime.Serialization.Json; 泛型类型T应该在数据契约中更多地序列化

public class JsonSerializerDeserializer<T> where T : class
{
    private readonly DataContractJsonSerializer jsonSerializer;

    public JsonSerializerDeserializer()
    {
        this.jsonSerializer = new DataContractJsonSerializer(typeof(T));
    }

    public string Serialize(T t)
    {
        using (var memoryStream = new MemoryStream())
        {
            this.jsonSerializer.WriteObject(memoryStream, t);
            memoryStream.Position = 0;
            using (var sr = new StreamReader(memoryStream))
            {
                return sr.ReadToEnd();
            }
        }
    }

    public T Deserialize(string objectString)
    {
        using (var ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes((objectString))))
        {
            return (T)this.jsonSerializer.ReadObject(ms);
        }
    }
}

另一个非常简单的解决方案是使用Newtonsoft库。Json:

User user = JsonConvert.DeserializeObject<User>(jsonString);

在性能方面,我发现ServiceStack的序列化器比其他的快一些。它是ServiceStack中的JsonSerializer类。文本名称空间。

https://github.com/ServiceStack/ServiceStack.Text

ServiceStack通过NuGet包提供: https://www.nuget.org/packages/ServiceStack/


而不是仅仅作为一个对象发送。

创建一个可访问的公共属性类,并将数据发送给Webmethod。

[WebMethod]
public static void SaveTeam(useSomeClassHere user)
{
}

在ajax调用中使用相同的参数名称来发送数据。