C
C#8mo ago
gucbi

How to encapsulate the code that has been processed using the Newtonsoft Json library?

I used the Newtonsoft Json library to write data to a JSON file, but I don't know how to encapsulate this part of the code. How to encapsulate it? ####### JObject ArchiveBaseInfo = new JObject( new JProperty("Version", ArchiveVersion), new JProperty("Name", EncodeName), new JProperty("ID", PlayerID) ); File.WriteAllText(ArchiveFile, ArchiveBaseInfo.ToString()); // write JSON directly to a file using (StreamWriter file = File.CreateText(ArchiveFile)) using (JsonTextWriter writer = new JsonTextWriter(file)) { ArchiveBaseInfo.WriteTo(writer); }
5 Replies
Angius
Angius8mo ago
I have a few questions: 1. Why JObject shenanigans and not objects proper? 2. Why Newtonsoft? 3. Why are you writing to the file twice? 4. What do you mean by "encapsulate" here?
gucbi
gucbiOP8mo ago
1. I don't know if he can 2. There is no need to pursue NLog for this project, but I don't know of any other well-known libraries besides NLog 3. o. WriteTo (writer); Can it be deleted? 4. It can be directly called where needed, such as. a (cv, fg); Such or similar method calls
leowest
leowest8mo ago
2. he is not talking about NLog, Newtonsoft is old and slow used only for edge cases and faulty json these days. .NET comes with System.Text.Json out of the box which is the suggested.
MODiX
MODiX8mo ago
leowest
REPL Result: Success
using System.Text.Json;
var info = new ArchiveBaseInfo
{
Id = 10,
Version = "1.0",
Name = "Robot"
};
Console.WriteLine(JsonSerializer.Serialize(info));

public class ArchiveBaseInfo
{
public int Id {get;set;}
public string Version {get;set;}
public string Name {get;set;}
}
using System.Text.Json;
var info = new ArchiveBaseInfo
{
Id = 10,
Version = "1.0",
Name = "Robot"
};
Console.WriteLine(JsonSerializer.Serialize(info));

public class ArchiveBaseInfo
{
public int Id {get;set;}
public string Version {get;set;}
public string Name {get;set;}
}
Console Output
{"Id":10,"Version":"1.0","Name":"Robot"}
{"Id":10,"Version":"1.0","Name":"Robot"}
Quoted by
<@1102729783969861782> from #bot-spam (click here)
Compile: 492.813ms | Execution: 43.449ms | React with ❌ to remove this embed.
gucbi
gucbiOP8mo ago
Understood If it was "o. WriteTo (writer);" that caused writing twice, I think I know how to do it thank you for you help. I think I know how to improve it
Want results from more Discord servers?
Add your server