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.

1
  • 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). The easiest why would be to just use class instead of tuple Commented Jan 22, 2022 at 12:13

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Okay thanks ill use that.
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));   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.