如何将JSON对象转换为Custom C#对象?

时间:2010-02-11 18:30:37

标签: c# asp.net .net ajax json

是否有一种简单的方法可以使用通过AJAX传递的JSON对象填充我的C#对象?

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

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

接收JSON对象的C#WebMetod

[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; }
}

13 个答案:

答案 0 :(得分:194)

在C#中使用JSON的好方法是使用JSON.NET

来自Quick Starts & API Documentation

JSON.NET - Official site可帮助您解决问题。

如何使用它的一个例子:

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);
 }

答案 1 :(得分:157)

因为我们都喜欢一个内衬代码

Newtonsoft比java脚本序列化程序更快。 ...这个依赖于Newtonsoft NuGet包,它比默认的序列化器更受欢迎。

如果我们上课,请在下面使用。

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

没有课程然后使用动态

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

答案 2 :(得分:91)

要保持选项打开,如果您使用的是.NET 3.5或更高版本,这里有一个完整的示例,您可以直接使用Generics从框架中使用。正如其他人所提到的,如果它不仅仅是简单的对象,你应该真正使用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;

答案 3 :(得分:53)

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

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

一般来说,您可以使用下面的JavascriptSerializer类,或者为了更加灵活,可以使用各种Json框架(Jayrock JSON是一个很好的框架),以便于JSON操作。

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

答案 4 :(得分:37)

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

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

答案 5 :(得分:30)

以下两个示例使用

    System.Web.Script.Serialization 或下的
  1. JavaScriptSerializer System.Web.Helpers
  2. 下的
  3. Json.Decode

    示例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
            }
        }
    }
    

    用法:自定义C#对象的JSON对象

    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
            }
        }
    }
    

    用法:自定义C#对象的JSON对象

    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.NET Web   页{VERSION} \装配\ System.Web.Helpers.dll

    或者

      

    %ProgramFiles(x86)%\ Microsoft ASP.NET \ ASP.NET Web   页{VERSION} \装配\ System.Web.Helpers.dll

    希望这有帮助!

答案 6 :(得分:7)

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 Class,您可以阅读here

答案 7 :(得分:5)

使用JavaScriptSerializer()不如提供的通用解决方案严格:public static T Deserialize(string json)

将json传递给与您尝试转换为的Object定义不完全匹配的服务器时,这可能会派上用场。

答案 8 :(得分:2)

在性能方面,我发现ServiceStack的串行器比其他器件快一点。它是ServiceStack.Text命名空间中的JsonSerializer类。

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

ServiceStack可通过NuGet包获得: https://www.nuget.org/packages/ServiceStack/

答案 9 :(得分:1)

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

答案 10 :(得分:1)

JSON C# class generator on codeplex生成的类与NewtonSoftJS一起使用。

答案 11 :(得分:1)

JavaScript序列化程序:需要using 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);
    }
}

Data Contract Serializer:需要using System.Runtime.Serialization.Json; - 泛型类型T应该是可序列化的more on Data Contract

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);
        }
    }
}

答案 12 :(得分:0)

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

创建可访问的公共属性类,并将数据发送到Web方法。

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

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