0

I'm using JSON.NET to serialize class objects to a .txt file using:

public static void SaveDataToFile<T>(T data, string directory)
{
    JsonSerializerSettings settings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore, TypeNameHandling = TypeNameHandling.All };

    //Save as JSON string to file
    System.IO.File.WriteAllText(directory, JsonConvert.SerializeObject(data, typeof(T), settings));
}

But the .txt file has null/no data inside (viewing in Notepad++):

File.txt

What would make a serialized object have data like this?

  • `NullValueHandling = NullValueHandling.Ignore` means that properties whose value is `null` (in c#) should not be serialized. You appear to have actual [unicode NULL characters](http://www.fileformat.info/info/unicode/char/0000/index.htm) in your text strings. This looks like an [encoding problem](https://msdn.microsoft.com/en-us/library/ms404377%28v=vs.110%29.aspx), make sure you are reading and writing the JSON with the same encoding (ideally utf-8). – dbc Jun 02 '16 at 08:22
  • In specific, make sure Nodepad++ is reading the file in utf-8 rather than ANSI. See [change the default encoding for notepad++](https://stackoverflow.com/questions/5090845/change-the-default-encoding-for-notepad). – dbc Jun 02 '16 at 08:25
  • @dbc "make sure you are reading and writing the JSON with the same encoding" How do I do this with JSON.NET (can't find anything online about it) – ShockDismantler Jun 02 '16 at 11:55
  • It's `WiteAllText` that does the encoding. Use [`File.WriteAllText(String, String, Encoding)`](https://msdn.microsoft.com/en-us/library/ms143376.aspx) and pass `new UTF8Encoding(false)` for the `Encoding`. Then open the file in notepad++ as explained in [change the default encoding for notepad++](https://stackoverflow.com/questions/5090845/change-the-default-encoding-for-notepad). – dbc Jun 02 '16 at 17:53

0 Answers0