Cannot implicitly convert type 'ulong[]' to 'Newtonsoft.Json.Linq.JToken'

Viewed 294

I am trying to save ulong[] to my json file.

This is my code:

ulong[] ts = new ulong[3];
ts[0] = 749076952626757682
ts[1] = 849076952626757682
ts[2] = 949076952626757682

var json = string.Empty;
json = File.ReadAllText(@"file.json");
dynamic jsonObj = JsonConvert.DeserializeObject(json);

jsonObj["whitelistedChannels"] = ts; //this is the line on which i'm getting the error
tring output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
File.WriteAllText(configFile, output);

This is my json

{
  "test": []
}

I want my json file to look like this:

{
  "test": [749076952626757682,849076952626757682,949076952626757682]
}

How can i do that? Thanks in advance.

3 Answers

Try this:

ulong[] ts = new ulong[3];
ts[0] = 749076952626757682;
ts[1] = 849076952626757682;
ts[2] = 949076952626757682;

var obj = new { test = ts };

//pick only one of the next two lines
var json = JsonConvert.SerializeObject(obj); //from Newtonsoft.Json
var json = JsonSerializer.Serialize(obj); //from System.Text.Json

File.WriteAllText("filename.json", json);

If you don't want to create a special class to represent your json structure, you can deserialize to JObject and use Add method to add new property using JToken.FromObject:

var jObj = JsonConvert.DeserializeObject<JObject>(json); // or use `JObject.Parse`
ulong[] ts = new ulong[3];
ts[0] = 749076952626757682;
ts[1] = 849076952626757682;
ts[2] = 949076952626757682;
jObj.Add("whitelistedChannels", JToken.FromObject(ts));

or set existing one like this (actually will work for addition also):

jObj["test"] = JToken.FromObject(ts);

You can create a class to deserialize the content of your file and then add the data with the existing data and rewrite it to the file. Below is the sample code

Create a class

public class DataToWrite
{
   public List<ulong> whitelistedChannels { get; set; }
}

Then in your code

var json = File.ReadAllText(@"file.json");
var jsonObj = JsonConvert.DeserializeObject(json);

jsonObj.whitelistedChannels.AddRange(ts);
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
File.WriteAllText(configFile, output);

Initial data in the file

{
  "whitelistedChannels": []
}

After writing data to your file

{
  "whitelistedChannels": [
    749076952626757682,
    849076952626757682,
    949076952626757682
  ]
}
Related