Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

242
Views
C # Newtonsoft no puede modificar la matriz en el archivo JSON

Tengo un archivo JSON de este esquema. Esto tiene una matriz llamada cuentas.

 { "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" ] }

Estoy usando .NET framework. También uso la biblioteca newtonsoft. Quiero reemplazar esa matriz con una matriz C # String. La matriz de cadenas está codificada porque quiero probarla aquí. Esto no tiene errores de compilación. Hay un error de tiempo de ejecución.

 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); }

Quiero saber cómo escribir una matriz de cadenas en un archivo como una matriz json

Este es el error. Leí la documentación de newtonsoft pero no pude encontrar ninguna solución.

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

su conversión de tipos es incorrecta. La forma de la bestia es usar el objeto C# como se muestra a continuación. Crear una clase para datos json

 public class jsonData { public string UplayExecutable { get; set; } public string foo { get; set; } public int OpeningTime { get; set; } public string[] accounts { get; set; } }

Ahora, escriba el código para leer el archivo json, actualice el valor de las cuentas y vuelva a escribir en el archivo.

 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);
over 4 years ago · Santiago Trujillo Report

0

Sí, no puede convertir implícitamente una cadena [] en un JContainer, la forma en que lo soluciona es asignando un JArray con valores de cadena [] dentro. Aquí hay una solución para su código

 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);

Sin embargo, no necesitamos usar escritura dinámica aquí, solo podemos analizar el JSON, reemplazar la matriz y luego recuperar el json. al igual que

 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) );
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!