I have object in my app in c# i need to serialize it to JSON but I need to custom the result json to be like below :
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; }
}
I need to convert it to
{
"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."
}
}
the number is shown in json is StatusNo in my class I use this method to serialize the class
new JavaScriptSerializer().Serialize(model)
Thanks to my mental powers, I would guess, that you have a list of OrderStatus
and that the key in your resulting json is the statusNo
property of your C# class.
To get a specific structure as JSON you should always create special classes that match the structure and convert between your classes and at the end use the default JSON serialization process. In your case it could look something like this:
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; }
}
Some other related tips: