I have a JSON file from this schema. This has an array called accounts.
{
"UplayExecutable": "C:\\Program Files (x86)\\Ubisoft\\Ubisoft Game Launcher\\UbisoftConnect.exe",
"foo": "barr",
"OpeningTime": 8,
"accounts": [
"abc@a.com , testpass",
"rumirad@gmail.com , password2",
"rumirad@outlook.com , password3",
"rumirad@test.com , password3"
]
}
I am using .NET framework.I also use the newtonsoft library. I want to replace that array with a C # String array. The string array is hard-coded because I want to test it here. This has no compile errors. There is a runtime error.
private void button1_Click(object sender, EventArgs e)
{
string json = File.ReadAllText("data.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
string[] accs = { "hi@hi.com , testpass", "hey@hey.com , abcd123", "hello@hello.com , hi123" };
jsonObj["accounts"] = accs;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("data.json", output);
}
I want to know how to write a string array to a file as a json array
This is the error .I read the newtonsoft documentation but i could not find any solution
your type casting is wrong. Beast way is to use c# object like below. Create one class for json data
public class jsonData
{
public string UplayExecutable { get; set; }
public string foo { get; set; }
public int OpeningTime { get; set; }
public string[] accounts { get; set; }
}
Now, write code for reading json file, update accounts value and write back to file.
string json = File.ReadAllText("data.json");
var jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<jsonData>(json);
string[] accs = { "hi@hi.com , testpass", "hey@hey.com , abcd123", "hello@hello.com , hi123" };
jsonObj.accounts = accs;
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("data.json", jsonString);
Yes you cannot implicitly cast string[] to a JContainer the way you fix it is by assigning a JArray with string[] values inside., here is a fix to your code
string json = File.ReadAllText("data.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
string[] accs = { "hi@hi.com , testpass", "hey@hey.com , abcd123", "hello@hello.com , hi123" };
jsonObj["accounts"] = new JArray(accs);
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("data.json", output);
However we dont need to use dynamic typing here, we can just parse the JSON, replace the array then get the json back. like so
string json = File.ReadAllText("data.json");
var jObject = JObject.Parse(json);
string[] accs = { "hi@hi.com , testpass", "hey@hey.com , abcd123", "hello@hello.com , hi123" };
jObject["accounts"] = new JArray(accs);
File.WriteAllText("data.json", jObject.ToString(Newtonsoft.Json.Formatting.Indented) );