我的應用程式中有物件在 c# 我需要將它序列化為 JSON 但我需要自定義結果 json 如下所示:
My class :
public class OrderStatus
{
public string title { get; set; }
public int statusNo { get; set; }
public string description { get; set; }
public string message { get; set; }
public string icon { get; set; }
}
我需要將其轉換為
{
"1": {
"icon": "orange_warning",
"title": "Pending Processing",
"message":
"We are processing your payment on our end which could take up to 30 minutes",
"description":
"Feel free to continue shopping while we process your payment. You can check the status of your order in Order History at any time."
},
"2": {
"icon": "done_success",
"title": "Order Successfully Placed",
"message": "",
"description":
"We have sent an email to your email address confirming your order."
}
}
json 中顯示的數字是我的類中的 StatusNo 我使用此方法來序列化類
new JavaScriptSerializer().Serialize(model)
uj5u.com熱心網友回復:
多虧了我的智力,我猜您有一個串列,OrderStatus并且生成的 json 中的鍵是statusNo您的 C# 類的屬性。
要獲得特定的 JSON 結構,您應該始終創建與結構匹配的特殊類并在您的類之間進行轉換,最后使用默認的 JSON 序列化程序。在您的情況下,它可能看起來像這樣:
public static class Program
{
static void Main()
{
var orders = new List<OrderStatus>
{
new OrderStatus
{
title = "Pending Processing",
statusNo = 1,
description = "Feel free to continue shopping while we process your payment. You can check the status of your order in Order History at any time.",
message = "We are processing your payment on our end which could take up to 30 minutes",
icon= "orange_warning",
},
new OrderStatus
{
title = "Order Successfully Placed",
statusNo = 2,
description = "We have sent an email to your email address confirming your order.",
message = "",
icon= "done_success",
},
};
var jsonStructure = orders
.ToDictionary(order => order.statusNo, order => new OrderStatusJson { icon = order.icon, title = order.title, message = order.message, description = order.description });
var json = JsonSerializer.Serialize(jsonStructure, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json);
Console.ReadLine();
}
}
public class OrderStatusJson
{
public string icon { get; set; }
public string title { get; set; }
public string message { get; set; }
public string description { get; set; }
}
public class OrderStatus
{
public string title { get; set; }
public int statusNo { get; set; }
public string description { get; set; }
public string message { get; set; }
public string icon { get; set; }
}
其他一些相關提示:
- 在 C# 端使用 PascalCase 作為屬性名稱。兩種常用的 JSON 序列化程式(Newtonsoft 和 Microsoft)都可以配置為對雙方使用正確的大小寫。
- 如果需要一堆不同型別之間的映射,你應該看看AutoMapper。
uj5u.com熱心網友回復:
您要從該類轉換的結構不和諧。轉換它的好方法是改變你的結構。為此,您可以使用Json2csharp.com。復制您的 json 結構并過去。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/345090.html
