1、创建-用匿名对象创建 JObject JObject ob = JObject.FromObject(new { RPT_ID = "getList", pageSize = 100, auth = "myAuthCode", PARAS = new { IDCard = cardNo } }); 2、合并其他对象到属性 JObject obj = new JObject(); obj.Add("name", "张三"); obj.Add("birthday", DateTime.Now); //合并其他对象到当前对象的属性 obj.Add("content", JToken.FromObject(new { code = "zhangsan" })); 3、合并其他对象的属性,到当前对象 //合并其他 JToken token = JToken.FromObject(new { code = "zhangsan" }); JObject obj2 = JObject.FromObject(new { code = "lisi" }); obj.Merge(obj2); 4、错误的写法 直接Add对象,会抛出异常:Could not determine JSON object //直接添加对象失败:Could not determine JSON object //obj.Add(new { // code="zhangsan" //}); 5、简单json对象 { "shp_flg": "0", "fm_date": "2018-04-18T00:00:00Z", "to_date": "2018-04-18T00:00:00Z", "emp_no": "008", "emp_nme_en": "Visitor 6", "shift": "事假", "work_time": 35, "remark": "xyz" } JObject jo = JObject.Parse(paramsStr); //paramsStr - json字符串名字 //下面是各种不同写法,但是结果一样 string shp_flg = jo["shp_flg"].ToString(); string fm_date = jo["fm_date"].ToString("yyyy-MM-dd"); string to_date = jo.Value<DateTime>("to_date").ToString("yyyy-MM-dd"); string emp_no = jo["emp_no"].ToString(); string shift = jo.Value<string>("shift"); int work_time = jo.Value<int>("work_time"); string remark = jo.Value<string>("remark"); 6、嵌套json对象解析 json 格式的字符串解析 格式化 { "input": { "size": 193156, "type": "image/png" }, "output": { "size": 59646, "type": "image/png", "width": 487, "height": 284, "ratio": 0.3088, "url": "https://api.tinify.com/output/hrqtghqtv0ab4qgv.png" } } // json解析 嵌套格式 Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonText); decimal input_size = Convert.ToDecimal(jobject["input"]["size"]);//193156, 输入图片大小 string input_type = jobject["input"]["type"].ToString();// "image/png",输入图片类型 decimal output_size = Convert.ToDecimal(jobject["output"]["size"]);// 59646, 图片大小 string output_type = jobject["output"]["type"].ToString();//"image/png", 图片类型 string output_width = jobject["output"]["width"].ToString();//487, 宽度 string output_height = jobject["output"]["height"].ToString();//284, 高度 string output_ratio = jobject["output"]["ratio"].ToString();//0.3088, 压缩率=Convert.ToString((1-0.3088)*100)+"%"; string output_url = jobject["output"]["url"].ToString();//"https://api.tinify.com/output/hrqtghqtv0ab4qgv.png" WebEnh.Core.Net.HttpProc.WebClient wc = new WebEnh.Core.Net.HttpProc.WebClient(); wc.DownloadFile(output_url, download_filename);
C# Newtonsoft.Json JObject创建匿名对象
最新推荐文章于 2024-09-25 08:00:00 发布