البرمجة

كيفية إضافة قيمة إلى مفتاح JSON في C#

To insert a value into a key of a JSON object in C#, you can deserialize the JSON string into a Dictionary, modify the dictionary, and then serialize it back into a JSON string. Here’s how you can do it:

csharp
using System; using System.Collections.Generic; using Newtonsoft.Json; class Program { static void Main() { // Your JSON string string json = @" { ""name"": ""Allan"", ""lastname"": ""Zé Store"", ""type"": ""J"", ""street"": ""Rua Abdon Batista, 121"", ""emails"": [ { ""email"": ""[email protected]"" }, { ""email"": ""[email protected]"" } ], ""phone"": [ { ""number"": ""(11) 98765-4321"" }, { ""number"": ""(47) 9876-5432"" } ] }"; // Deserialize JSON string into a dictionary var dict = JsonConvert.DeserializeObjectstring, object>>(json); // Insert a new value into the "emails" key ((List<object>)dict["emails"]).Add(new Dictionary<string, string> { { "email", "[email protected]" } }); // Serialize the dictionary back into a JSON string string updatedJson = JsonConvert.SerializeObject(dict, Formatting.Indented); Console.WriteLine(updatedJson); } }

In this example, I’ve shown how to add a new email address to the “emails” key. You can use a similar approach to modify other keys or add new keys to the JSON object.

المزيد من المعلومات

بالطبع! يمكنك أيضًا استخدام مكتبة Newtonsoft.Json في C# لإدراج قيم جديدة في مفتاح JSON بدلاً من تعديل القيمة الموجودة. على سبيل المثال، إذا أردت إضافة مفتاح جديد إلى الكائن JSON، يمكنك استخدام الشيفرة التالية:

csharp
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; class Program { static void Main() { // Your JSON string string json = @" { ""name"": ""Allan"", ""lastname"": ""Zé Store"", ""type"": ""J"", ""street"": ""Rua Abdon Batista, 121"", ""emails"": [ { ""email"": ""[email protected]"" }, { ""email"": ""[email protected]"" } ], ""phone"": [ { ""number"": ""(11) 98765-4321"" }, { ""number"": ""(47) 9876-5432"" } ] }"; // Parse JSON string to JObject JObject obj = JObject.Parse(json); // Add a new key-value pair obj["newKey"] = "newValue"; // Serialize JObject back to JSON string string updatedJson = obj.ToString(Formatting.Indented); Console.WriteLine(updatedJson); } }

هذا سيضيف مفتاحًا جديدًا يسمى “newKey” بقيمة “newValue” إلى الكائن JSON. يمكنك استخدام هذه الطريقة لإضافة مفاتيح جديدة أو تحرير القيم الموجودة في الكائن JSON بسهولة.

مقالات ذات صلة

زر الذهاب إلى الأعلى

هذا المحتوى محمي من النسخ لمشاركته يرجى استعمال أزرار المشاركة السريعة أو تسخ الرابط !!