簡體   English   中英

沒有屬性的C#json序列化和反序列化

[英]C# json serialization and deserialization without attributes

是否可以在不為每個所需屬性指定DataMember屬性的情況下序列化和反序列化類及其繼承?

是。 您可以使用.NET JavaScriptSerializer類,也可以使用第三方庫,例如Json.Net

這是使用JavaScriptSerializer的示例:

using System;
using System.Web.Script.Serialization;

class Program
{
    static void Main(string[] args)
    {
        DerivedClass dc = new DerivedClass
        {
            Id = 1,
            Name = "foo",
            Size = 10.5
        };

        JavaScriptSerializer ser = new JavaScriptSerializer();
        string json = ser.Serialize(dc);
        Console.WriteLine(json);
        Console.WriteLine();

        DerivedClass dc2 = ser.Deserialize<DerivedClass>(json);
        Console.WriteLine("Id: " + dc2.Id);
        Console.WriteLine("Name: " + dc2.Name);
        Console.WriteLine("Size: " + dc2.Size);
    }
}

class BaseClass
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class DerivedClass : BaseClass
{
    public double Size { get; set; }
}

輸出:

{"Size":10.5,"Id":1,"Name":"foo"}

Id: 1
Name: foo
Size: 10.5

是的,有可能,我將通過編寫asp.net代碼給您一個例子:

C#代碼:

public class a{
    public prop int id
}

public class b: public a{
    public prop string name 
}

asp.net代碼:

@model b    // for taking b as model in this view

<form action="action" method="post" id="myForm">
    enter id : @Html.TextboxFor(m=>m.id)
    enter name : @Html.TextboxFor(m=>m.name)
<input type="submit" id="send" value="submit">
</form>

jQuery代碼:

$("#send").click(function(e)){
    e.preventDefault();
    $.ajax({
    url:"myURL",
    data: $("#myForm").serialize(),     // for serialization of whole form or object b
    success: function(result){},
    }

因此,這里的行[data:$(“#myForm”)。serialize()]序列化整個對象b或形式為“ myForm”。 此處無需序列化特定屬性。 希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM