C#解析U8C返回的JSON

一、业务背景

最近项目需要与U8c对接,实现增删改查,借此机会,梳理一下C#解析Json字符串的问题。
这篇文章,先以查询接口为例。

二、查询接口

首先以一个查询接口为例。
C#解析U8C返回的JSON_第1张图片
访问U8c接口

string res = sendPost(url, strdata, trantype, system, username, password);

查看接口返回的数据
由于方法返回的是字符串
在这里插入图片描述

我们查看接口返回数据

在这里插入图片描述

我们可以看到,字符串数据。
所以第一步,需要将字符串转为JSON对象

 JObject res_obj = JObject.Parse(res);

JObject.Parse 是一个.NET库中的方法,用于将字符串转换为 JSON 对象。它可以解析符合 JSON 格式的字符串,并将其转换为 JObject 对象,以便在代码中进行处理和操作。这个方法在开发中常用于处理 JSON 数据。例如:
string jsonString = “{“name”:“John”,“age”:30,“city”:“New York”}”;
JObject jsonObject = JObject.Parse(jsonString);
通过使用 JObject.Parse,我们可以将 jsonString 字符串解析为 JSON 对象,并且可以通过键值对的方式访问和操作其中的属性。

看一下效果
在这里插入图片描述
拿出来看一下

{
	{
		"status": "success",
		"data": "{\"allcount\":2,\"retcount\":2,\"queryallsql\":\"select pk_invbasdoc from bd_invbasdoc where 1=1\",\"datas\":[{\"parentvo\":{\"pk_corp\":\"0001\",\"invcode\":\"TEST01\",\"invname\":\"灭火器\",\"pk_invcl\":\"0001F8100000000009RX\",\"invclcode\":\"39\",\"invclname\":\"安全环保\",\"pk_measdoc\":\"0001F810000000000PM5\",\"meascode\":\"1\",\"measname\":\"台\",\"pk_taxitems\":\"40040000000000000077\",\"taxitemscode\":\"2909\",\"taxitemsname\":\"其它采掘业\",\"unitvolume\":\"0.00000000\",\"unitweight\":\"0.00000000\",\"laborflag\":false,\"discountflag\":false,\"setpartsflag\":false,\"asset\":false,\"iselectrans\":false,\"isretail\":false,\"assistunit\":false,\"autobalancemeas\":false,\"ismngstockbygrswt\":false,\"isstorebyconvert\":false,\"creator\":\"17799197770\",\"creatorname\":\"陈疆\",\"createtime\":\"2023-12-14 20:06:17\",\"sealflag\":false,\"pk_invbasdoc\":\"0001F810000000000PM8\",\"ts\":\"2023-12-14 20:06:17\",\"dr\":\"0\"},\"childrenvo\":[]},{\"parentvo\":{\"pk_corp\":\"0001\",\"invcode\":\"802601001\",\"invname\":\"化工焦\",\"pk_invcl\":\"0001F8100000000009SM\",\"invclcode\":\"802601\",\"invclname\":\"焦炭-化工焦\",\"pk_measdoc\":\"0001F810000000000PM7\",\"meascode\":\"2\",\"measname\":\"吨\",\"pk_taxitems\":\"40040000000000000042\",\"taxitemscode\":\"1101\",\"taxitemsname\":\"生铁\",\"unitvolume\":\"0.00000000\",\"unitweight\":\"0.00000000\",\"laborflag\":false,\"discountflag\":false,\"setpartsflag\":false,\"asset\":false,\"iselectrans\":false,\"isretail\":false,\"assistunit\":false,\"autobalancemeas\":false,\"ismngstockbygrswt\":false,\"isstorebyconvert\":false,\"creator\":\"17799197770\",\"creatorname\":\"陈疆\",\"createtime\":\"2023-12-14 20:07:07\",\"sealflag\":false,\"pk_invbasdoc\":\"0001F810000000000PMB\",\"ts\":\"2023-12-14 20:07:07\",\"dr\":\"0\"},\"childrenvo\":[]}]}",
		"taskNumber": "202312150024"
	}
}

我们得到JObject对象之后,开始取值

foreach (JObject item in datas)
{
    // 在这里可以对 item 进行操作
}

我们取出status,判断状态是否成功,如果成功,将data值拿出

string data = res_obj.Value<string>("data");

其实从返回的数据,我们就可以看到
在这里插入图片描述
data里面的数据是字符串,我们再次转成JObject对象。

JObject data_obj = JObject.Parse(data);

然后取值。

JArray datas = data_obj.Value<JArray>("datas");

在这里插入图片描述
拿出来看一看

{
	[{
			"parentvo": {
				"pk_corp": "0001",
				"invcode": "TEST01",
				"invname": "灭火器",
				"pk_invcl": "0001F8100000000009RX",
				"invclcode": "39",
				"invclname": "安全环保",
				"pk_measdoc": "0001F810000000000PM5",
				"meascode": "1",
				"measname": "台",
				"pk_taxitems": "40040000000000000077",
				"taxitemscode": "2909",
				"taxitemsname": "其它采掘业",
				"unitvolume": "0.00000000",
				"unitweight": "0.00000000",
				"laborflag": false,
				"discountflag": false,
				"setpartsflag": false,
				"asset": false,
				"iselectrans": false,
				"isretail": false,
				"assistunit": false,
				"autobalancemeas": false,
				"ismngstockbygrswt": false,
				"isstorebyconvert": false,
				"creator": "17799197770",
				"creatorname": "xx",
				"createtime": "2023-12-14 20:06:17",
				"sealflag": false,
				"pk_invbasdoc": "0001F810000000000PM8",
				"ts": "2023-12-14 20:06:17",
				"dr": "0"
			},
			"childrenvo": []
		},
		{
			"parentvo": {
				"pk_corp": "0001",
				"invcode": "802601001",
				"invname": "化工焦",
				"pk_invcl": "0001F8100000000009SM",
				"invclcode": "802601",
				"invclname": "焦炭-化工焦",
				"pk_measdoc": "0001F810000000000PM7",
				"meascode": "2",
				"measname": "吨",
				"pk_taxitems": "40040000000000000042",
				"taxitemscode": "1101",
				"taxitemsname": "生铁",
				"unitvolume": "0.00000000",
				"unitweight": "0.00000000",
				"laborflag": false,
				"discountflag": false,
				"setpartsflag": false,
				"asset": false,
				"iselectrans": false,
				"isretail": false,
				"assistunit": false,
				"autobalancemeas": false,
				"ismngstockbygrswt": false,
				"isstorebyconvert": false,
				"creator": "17799197770",
				"creatorname": "xx",
				"createtime": "2023-12-14 20:07:07",
				"sealflag": false,
				"pk_invbasdoc": "0001F810000000000PMB",
				"ts": "2023-12-14 20:07:07",
				"dr": "0"
			},
			"childrenvo": []
		}
	]
}

下面是一个数组
使用for循环,进行取值

foreach (JObject item in datas)
{
}

取出第一个Jobject对象的parentvo的值

 JObject parentvo = item.Value<JObject>("parentvo");

拿出字段值

invclcode = parentvo.Value<string>("invcode");
invclname = parentvo.Value<string>("invclname");

看一下是否取成功
在这里插入图片描述
成功!!!

三、完整代码

查询方法:

   public ActionResult WLQuery()
   {
  
       string url = "http://xxxxx/u8cloud/api/uapbd/invbasdoc/query";
       string username = "xx";
       string password = "5xx70e2bf5xx84exx2c731a";
       string system = "xxxx";
       string trantype = "undefined";
       string strdata = string.Empty;
       string invclcode = string.Empty;//cinvclasscode 存货分类编码
       string invclname = string.Empty;//cinvclassname存货分类名称
       string invshortname = string.Empty;//cinvname 存货简称
       string invspec = "";//cinvstd 型号
       string meascode = "";//cunit 主计量单位
       string creator = string.Empty;//创建人
       string creatorname = string.Empty;//cmaker 创建人名称
       string createtime = string.Empty;
       string sql = string.Empty;
       IDatabase db = DataFactory.Database();
       DbTransaction trans = db.BeginTrans();
       var data_in = new
       {

       };
       strdata = JsonConvert.SerializeObject(data_in);
       strdata = strdata.Replace("null", "");

       string res = sendPost(url, strdata, trantype, system, username, password);
       JObject res_obj = JObject.Parse(res);
       if(res_obj.Value<string>("status").ToString() == "success")
       {
           string data = res_obj.Value<string>("data");
           JObject data_obj = JObject.Parse(data);
           JArray datas = data_obj.Value<JArray>("datas");

           foreach (JObject item in datas)
           {
               JObject parentvo = item.Value<JObject>("parentvo");
                invclcode = parentvo.Value<string>("invcode");
                invclname = parentvo.Value<string>("invclname");
                invshortname = parentvo.Value<string>("invshortname");
                invspec = parentvo.Value<string>("invspec");
               meascode = parentvo.Value<string>("measname");
               creator = parentvo.Value<string>("creator");
               creatorname = parentvo.Value<string>("creatorname");
               createtime = parentvo.Value<string>("createtime");

               sql = $"insert into ba_inventory_e  (id,ddate,cinvclasscode,cinvclassname,cinvname,cinvstd,cunit,cmaker) values(newid(),'{createtime}','{invclcode}','{invclname}','{invshortname }','{invspec}','{meascode}','{creatorname}')";
               string isOK = db.ExecuteSql(new StringBuilder(sql));
               if (!"OK".Equals(isOK.ToUpper()))
               {
                   return Content(new JsonMessage { Success = false, Code = "-1", Message = "插入物料档案失败!" + isOK }.ToJson());
                   db.Rollback();
               }
           }
       }
       db.Commit();
       return Content(new JsonMessage { Success = true, Code = "1", Message = "U8C物料档案查询并录入OA系统成功!" }.ToJson());
   }

http访问方法

  public string sendPost(string url, string json, string trantype, string system, string usercode, string password)
  {
      System.IO.Stream stream = null;
      StreamReader reader = null;
      try
      {
          Encoding encoding = Encoding.UTF8;
          HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
          request.Method = "POST";
          request.Accept = "text/html, application/xhtml+xml, */*";
          request.ContentType = "application/json";

          request.Headers["trantype"] = trantype;
          request.Headers["system"] = system;
          request.Headers["usercode"] = usercode;
          request.Headers["password"] = password;

          byte[] buffer = encoding.GetBytes(json);
          request.ContentLength = buffer.Length;
          request.GetRequestStream().Write(buffer, 0, buffer.Length);
          HttpWebResponse response = (HttpWebResponse)request.GetResponse();
          using (reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
              return reader.ReadToEnd();
      }
      catch (Exception ex)
      {
          Console.WriteLine(ex.Message);
      }
      finally
      {
          //if (writer != null) writer.Close();
          if (stream != null) stream.Close();
          if (reader != null) reader.Close();
      }
      return null;
  }

你可能感兴趣的:(C#,c#,json,服务器)