C#处理json的一些方法

Posted by kzdgt on Tuesday, August 29, 2023

C#处理json的一些方法

string json = @"{
  'channel': {
    'title': 'Star Wars',
    'link': 'http://www.starwars.com',
    'description': 'Star Wars blog.',
    'obsolete': 'Obsolete value',
    'item': []
  }
}";

JObject rss = JObject.Parse(json);

JObject channel = (JObject)rss["channel"];

channel["title"] = ((string)channel["title"]).ToUpper();
channel["description"] = ((string)channel["description"]).ToUpper();

channel.Property("obsolete").Remove();

channel.Property("description").AddAfterSelf(new JProperty("new", "New value"));

JArray item = (JArray)channel["item"];
item.Add("Item 1");
item.Add("Item 2");

Console.WriteLine(rss.ToString());
// {
//   "channel": {
//     "title": "STAR WARS",
//     "link": "http://www.starwars.com",
//     "description": "STAR WARS BLOG.",
//     "new": "New value",
//     "item": [
//       "Item 1",
//       "Item 2"
//     ]
//   }
// }
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

class Program
{
    static void Main(string[] args)
    {
        string json = "{ \"aaa\": { \"bbb\": \"original value\" } }";
        JObject jObject = JObject.Parse(json);

        if (jObject["aaa"] != null)
        {
            Console.WriteLine("Node 'aaa' exists.");
            var aaa = jObject["aaa"];
            if (aaa?["bbb"] != null)
            {
                Console.WriteLine("Node 'bbb' exists. Modifying its value...");
                aaa["bbb"] = "c";
            }
            else
            {
                Console.WriteLine("Node 'bbb' does not exist.");
            }
        }
        else
        {
            Console.WriteLine("Node 'aaa' does not exist.");
        }

        string modifiedJson = jObject.ToString();
        Console.WriteLine("Modified JSON: " + modifiedJson);
    }

}

「真诚赞赏,手留余香」

kzdgt Blog

真诚赞赏,手留余香

使用微信扫描二维码完成支付