'Named List values on JSON.SerializeObject

i want to convert a List to JSON.

var bundledChats = new List<(int chatId, string chatName, Array chatParticipants)>();
bundledChats.Add((
        chatId: 1, 
        chatName: "Random Name"
        chatParticipants: [0, 1, 2, 3]));

Console.WriteLine(JsonConvert.SerializeObject(bundledChats));

Thats my Result:

[{"Item1":1,"Item2":"Chat Nummer #1","Item3":[28,200,111]}]

But i want to name Item_1... like the values that i set.



Solution 1:[1]

Add JsonData class

public class JsonData
{
   public int ChatId { get; set; }

   public string ChatName { get; set; }

   public int[] ChatParticipants { get; set; }
}

Now use

var bundledChats = new List<>()
{ 
  new JsonData() { ChatId = 1, ChatName = "Random Name", ChatParticipants =  new int[0, 1, 2, 3] }
};
string json = JsonConvert.SerializeObject(bundledChats);

Solution 2:[2]

the code you posted is not valid, it can not be compiled. Try this

var bundledChats = new[] { new {
            chatId= 1,
            chatName= "Random Name",
            chatParticipants = new int[] { 0, 1, 2, 3}}}; //.ToList() if you need a list

Console.WriteLine(JsonConvert.SerializeObject(bundledChats));

result

[{"chatId":1,"chatName":"Random Name","chatParticipants":[0,1,2,3]}]

or if you have the original data as tulip, you have to fix it and convert to anonymous type before serialization

var bundledChatsList = bundledChats
.Select(c => new {c.chatId, c.chatName, c.chatParticipants }).ToList();

Console.WriteLine(JsonConvert.SerializeObject(bundledChatsList));   

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Meysam Asadi
Solution 2