[英]Serialization of javascript function for c#
在我的c#類中,我有以下類:
public class Product
{
public int product_id;
public int quantity;
public string book_cost;
}
如果我使用JavaScriptSerializer
對其進行序列化,那么我會回來
{"product_id":0,"quantity":0,"book_cost":"hello"}
設置值后。
那是c#,但我怎么能序列化一個javascript函數來匹配呢?
我想將一個js函數解析為ac#class
示例....如果我在c#中有一個類並且我想將它發送到其他Web服務器,我可以序列化該對象並使用JSON
var serializer = new JavaScriptSerializer();
serializer.Serialize(new Product());
public class Product
{
public int product_id = 0;
public int quantity = 0;
public string book_cost = "hello";
}
然后在另一邊我可以這樣:
var serializer = new JavaScriptSerializer();
Product p = serializer.Deserialize<Product>(products);
Console.WriteLine(p.product_id);
public class Product
{
public int product_id;
public int quantity;
public string book_cost;
}
它會打印出0,因為我創建了一個新產品類,其中包含來自另一個類的值,但是我希望一方是js(發送方),另一方是c#(接收方)
這里有更多的例子:
js方......
我有這個功能,我已經設置了這個值,但我會在運行時更改它們。
function Product(){
this.product_id = 0;
this.quantity = 0;
this.book_cost = "hello";
}
然后我想要從中生成我想要生成
{"product_id":0,"quantity":0,"book_cost":"hello"}
然后在另一方面,我想填充上面的Product類。 我只會使用字符串,整數和日期對象。 如果我在c#中序列化一個DateTime對象,它就會出現
{"date":"\/Date(-62135596800000)\/"}
您可以使用JSON.stringify方法在JSON中序列化對象。 就像是:
function Product() {
this.product_id = 0;
this.quantity = 0;
this.book_cost = "hello";
}
var p = new Product();
p.quantity = 5;
var json = JSON.stringify(p);
不要擔心日期格式。 任何好的序列化器都能識別各種日期表示。 不需要手動重新格式化任何東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.