net - 如何將JSON對象轉換為自定義C#對象?




jquery ajax asp net (10)

JSON.Net是您最好的選擇,但根據對象的形狀以及是否存在循環依賴關係,您可以使用JavaScriptSerializer或DataContractSerializer。

有沒有簡單的方法來填充我的C#對象與通過AJAX傳遞的JSON對象?

//這是使用JSON.stringify從頁面傳遞給C#WEBMETHOD的JSON對象

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

// C#WebMetod接收JSON對象

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

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應該在數據合約上更多地可序列化

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比java腳本串行器更快。 ...這個取決於Newtonsoft NuGet包,它比默認的序列化器更流行,更好。

如果我們有課,然後在下面使用。

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

沒有課程,然後使用動態

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

以下兩個例子都可以使用

  1. JavaScriptSerializerSystem.Web.Script.Serialization
  2. System.Web.Helpers下的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
        }
    }
}

用法:將 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.NET網頁{VERSION} \ Assemblies \ System.Web.Helpers.dll

要么

%ProgramFiles(x86)%\ Microsoft ASP.NET \ ASP.NET網頁{VERSION} \ Assemblies \ System.Web.Helpers.dll

希望這可以幫助!


另一個非常簡單的解決方案是使用庫Newtonsoft.Json:

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

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

JSON.NET 快速入門和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);
 }

為了讓您的選擇保持開放,如果您使用的是.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;

而不是僅僅發送一個對象。

創建可訪問的公共類別的屬性並將數據發送到Webmethod。

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

在ajax調用中使用相同的參數名稱來發送數據。


鑑於您的代碼示例,您不需要執行其他任何操作。

如果您將該JSON字符串傳遞給您的Web方法,它將自動解析JSON字符串並創建一個填充的User對像作為SaveTeam方法的參數。

一般來說,您可以像下面那樣使用JavascriptSerializer類,或者為了更加靈活,可以使用Json框架中的任何一種(Jayrock JSON是一個很好的框架),以實現簡單的JSON操作。

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

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閱讀。





json