0

So I am currently printing out json data to a file by doing this.

private void btnUnban_Click(object sender, RoutedEventArgs e)
        {
            BannedUsers user = lvBannedUsers.SelectedItem as BannedUsers;
            bannedUsernames.Remove((BannedUsers)user);
            lvBannedUsers.Items.Refresh();

            using (StreamWriter sw = new StreamWriter("banned-players.json"))
            {
                sw.Write("[" + Environment.NewLine);
                foreach (BannedUsers userdata in bannedUsernames)
                {
                    string serializedData = JsonConvert.SerializeObject(userdata);
                    sw.Write(serializedData + "," + Environment.NewLine);
                }
                sw.Write("]");

            }
        }

The issue is that when it prints out, it looks like this.

[
{"uuid":null,"name":"steffe","created":null,"source":null,"expires":null,"reason":null}
]

When it should be looking like this.

[
  {
    "uuid": "a7c1987f-022c-4310-bd32-21614e7e37b8",
    "name": "Stefan",
    "created": "2017-11-09 21:54:40 +0100",
    "source": "Server",
    "expires": "forever",
    "reason": "Banned by an operator."
  }
]

How do I properly indent the json data? Because when the external application reads the data it throws an error because it cant read it properly due to indentation issues.

Jordan Jones
  • 125
  • 10
  • are you displaying that json string to UI? if not, then why indentation is a matter? – Rahul Nov 10 '17 at 13:21
  • 1
    JsonConvert.SerializeObject() is an overloaded method. One of the possible methods has a Formatting enum parameter. Therefore, changing your call to "JsonConvert.SerializeObject(userdata,Formatting.Indented)" should fix your problem. PS: Reading the documentation is always handy: https://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_JsonConvert_SerializeObject.htm – redsoxfantom Nov 10 '17 at 15:26

0 Answers0