简体   繁体   中英

save JObject as Base64 Encoded file

I'm reading a Json file into a JObject myParams with this code. This works well

using (StreamReader file = File.OpenText("config.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
    JObject myParams = (JObject)JToken.ReadFrom(reader);
}

What I want is then to encode the information and save it back into another file. This code reads a file, encodes it and directly saves it. It works

using (StreamWriter w = new StreamWriter("filenameEncoded.bson", true))
    ​w.Write(Convert.ToBase64String(File.ReadAllBytes("filename.json")));

However I don't want to read a file and immediately encode it.

Instead I want to import myParams with the first piece of code, do some modifications to the JObject and then encode it and save it encoded in a file.

The problem is that then I cannot use Convert.ToBase64String on myParams since it expect bytes instead of a JObject.

How can I encode and save my JObject myParams into an encoded file?

You can pass the following parameter to your Convert.ToBase64String method call:

Encoding.UTF8.GetBytes(myParams.ToString(Formatting.None))
  • the ToString call on the JObject is overwritten to emit Json
  • the Formatting.None parameter will omit indentation
  • the Encoding.XYZ.GetGetBytes converts a string into a byte[]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM