1. 程式人生 > 其它 >c# 解析json字串

c# 解析json字串

解析格式1:

{
    "code": 200,
    "message": "操作成功",
    "data": {
        "Id": "123456"
    },
    "success": true
}

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;


public string CreateMessage(string url) { string ret = string.Empty; string consumerId = ""; try { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url); webReq.Method = "POST"; webReq.ContentType = "application/json"; webReq.Headers.Add("Authorization", "bearer ******"); Stream postData = webReq.GetRequestStream(); postData.Close(); HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse(); StreamReader sr = new StreamReader(webResp.GetResponseStream(), Encoding.UTF8); ret = sr.ReadToEnd();
//此處解析 JObject jsonObj = JObject.Parse(ret);
string code = jsonObj["code"].ToString();
if (code == "200") {
//拿到ID的值 consumerId = ((JObject)jsonObj["data"])["Id"].ToString(); } } catch (Exception ex) { //LogManager.LogInstance.WriteLog("時間:" + DateTime.Now + "/n 請求出錯原因" + ex.ToString()); } return consumerId; }

  解析格式2:

{
    "code": 200,
    "message": "操作成功",
    "data": [
        {
            "msgId": "123456",
            "msgType": "type1",
            "content": "{\"eventId\":\"20161111\",\"dateTime\":\"2021-06-17\"}"
        },
        {
            "msgId": "456789",
            "msgType": "type2",
            "content": "{\"eventId\":\"20161112\",\"dateTime\":\"2021-06-17\"}"
        }
]
}

  

public string GetWarningData(string consumerId)
        {
            string ret = string.Empty;
            try
            {
                string nUrl = "https://****/messages?consumerId=" + consumerId + "&autoCommit=true";
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(nUrl);
                webReq.Method = "POST";
                webReq.ContentType = "application/json";
                webReq.Headers.Add("Authorization", "bearer *******");
                //獲取服務端返回
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd().Trim();
                JObject jo = (JObject)JsonConvert.DeserializeObject(ret);
                string code = jo["code"].ToString();
               
                #region log日誌
                //儲存 拉取資料code值,通道ID,時間
                warninfoManageservice.SaveLog(code, consumerId);
                #endregion
                if (code == "200")
                {
                    JArray jar = JArray.Parse(jo["data"].ToString());
                    for (var i = 0; i < jar.Count; i++)
                    {
                        //每次只能存放一條資料在model中,否則會重複上傳資料
                        //如果將所有資料存放在model內,那麼需要將下面的物件拿到for迴圈外面
                        CarMessage obj = new CarMessage();
                        obj.captureCars = new List<captureCars>();
                        JObject j = JObject.Parse(jar[i].ToString());
                        string msgId = j["msgId"].ToString();
                        JObject con = JObject.Parse(jar[i]["content"].ToString());
                        string dt = con["dateTime"].ToString();
                        }
                    }
                }
                sr.Close();
            }
            catch (Exception ex)
            {

            }
            return ret;
        }