I am trying to write a dictionary to json file from C#, but the output is wrong, here is my method
public static List<Dictionary<string, int>> CreateGlobalVectorAndRareVectors(List<Article> articleList)
{
List<Dictionary<string, int>> vectoriRari = new List<Dictionary<string, int>>();
int i = 0;
foreach (Article art in articleList)
{
Dictionary<string, int> aux = new Dictionary<string, int>();
string[] title = art.Title1.Split(delimiterChars);
string[] text = art.Text1.Split(delimiterChars);
string[] completeText = title.Concat(text).ToArray();
completeText = completeText.Where(x => !string.IsNullOrEmpty(x)).ToArray();
foreach (var word in completeText)
{
if (!aux.ContainsKey(word))
{
aux.Add(word, 1);
}
else
{
aux.TryGetValue(word, out int tempValue);
aux[word] = tempValue 1;
}
}
string json = JsonConvert.SerializeObject(aux);
using (StreamWriter sw = File.CreateText(@".\..\..\..\OutputData\" art.FileNames[i] ".json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(sw, json);
}
i ;
vectoriRari.Add(aux);
}
return vectoriRari;
}
Here is the output I want to get
{
"USA": 1,
"Microsoft": 1,
"sees": 1
}
And this is the output I get
{
\"USA\": 1,
\"Microsoft\": 1,
\"sees\": 1
}
The question is how do I get rid of \ ? I am using the Newtonsoft.Json library for formating the json files.
CodePudding user response:
You're serializing it twice:
string json = JsonConvert.SerializeObject(aux);
using (StreamWriter sw = File.CreateText(@".\..\..\..\OutputData\" art.FileNames[i] ".json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(sw, json);
}
You've already got JSON from the first line - you're then encoding that JSON as a JSON string in the Serialize
call later.
You can make this much simpler:
string json = JsonConvert.SerializeObject(aux);
// TODO: Consider using Path.Combine instead
string path = @"..\..\..\OutputData\" art.FileNames[i] ".json";
File.WriteAllText(path, json);