0

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.

Serge
  • 40,935
  • 4
  • 18
  • 45
f1fty
  • 21
  • 3
  • 1
    Names in tuples are replaced after compilation, so IDE can move around and understand it from your code, but after compilation names are replaced with Item1, Item2... etc., so there is no way that serilizer gonna know what was there before, when program is executing. Here is the same topic, just about serilizing tuple not list [stackoverflow.com/a/57217505/3626160)](https://stackoverflow.com/questions/45932003/make-names-of-named-tuples-appear-in-serialized-json-responses/57217505#57217505). The easiest why would be to just use class instead of tuple – zipsonix Jan 22 '22 at 12:13

2 Answers2

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);
Meysam Asadi
  • 6,438
  • 3
  • 7
  • 17
0

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));   
Serge
  • 40,935
  • 4
  • 18
  • 45