gpt4 book ai didi

c# - 如何将字符串转换为 JSON

转载 作者:行者123 更新时间:2023-12-02 15:57:28 25 4
gpt4 key购买 nike

我以这种格式从源获取数据:

tag_id=0x770000001103AE6FF40DDF9D, tid=0xE2003412013DC2FFEE1223ED160E0142100548BBFF80DC60, user_data=0x12A7B70991000000006E5C05D37F0000, first=2018-12-03T22:52:16.218, antenna=1, rssi=-471, tid_authentic=AUTHENTIC, pw_authentic=AUTHENTIC

这就是我得到结果的方式:

private static void EventReceiveHandler(object sender, EventInfo eventInfo)
{
switch (eventInfo.Type)
{
case EventInfo.EventTypes.STATUS_TX_ACTIVE:
//StatusChanged(eventInfo.Data);
//AddMessageToTxt("STATUS REPORT " + eventInfo.Data);
break;
case EventInfo.EventTypes.TAG_REPORT:
AddMessageToTxt(string.Format("Time: {0} ~ STATUS REPORT: {1}", DateTime.Now, eventInfo.Data)); // "STATUS REPORT " + eventInfo.Data);
break;
case EventInfo.EventTypes.TAG_ARRIVE:
AddMessageToTxt("Tag Arrives " + eventInfo.Data);
break;
case EventInfo.EventTypes.TAG_DEPART:
AddMessageToTxt("Tag Depart " + eventInfo.Data);
break;
case EventInfo.EventTypes.TAG_RAW_ARRIVE:
AddMessageToTxt("Tag Raw Arrive " + eventInfo.Data);
break;
default:
AddMessageToTxt("NOTHING ELSE");
break;
}
}

如何将其转换为 json 格式,如下所示:

{
"tag_id":"0x770000001103AE6FF40DDF9D",
"tid":"0xE2003412013DC2FFEE1223ED160E0142100548BBFF80DC60",
"user_data":"0x12A7B70991000000006E5C05D37F0000",
"first":"2018-12-03T22:52:16.21",
"antenna":"1",
"rssi":"471",
"tid_authentic":"AUTHENTIC",
"pw_authentic":"AUTHENTIC"
}

谢谢。

最佳答案

var dictionary = new Dictionary<string, string>();
var parts = "tag_id=0x770000001103AE6FF40DDF9D, tid=0xE2003412013DC2FFEE1223ED160E0142100548BBFF80DC60, user_data=0x12A7B70991000000006E5C05D37F0000, first=2018-12-03T22:52:16.218, antenna=1, rssi=-471, tid_authentic=AUTHENTIC, pw_authentic=AUTHENTIC".Split(',');
var keyValues = parts
.Select(q => q.Split('='))
.Where(q => q.Length == 2)
.ToList();
keyValues.ForEach(q => dictionary[q[0].Trim()] = q[1].Trim());
var json = JsonConvert.SerializeObject(dictionary);
//json ==
//{
// "tag_id":"0x770000001103AE6FF40DDF9D",
// "tid":"0xE2003412013DC2FFEE1223ED160E0142100548BBFF80DC60",
// "user_data":"0x12A7B70991000000006E5C05D37F0000",
// "first":"2018-12-03T22:52:16.218",
// "antenna":"1",
// "rssi":"-471",
// "tid_authentic":"AUTHENTIC",
// "pw_authentic":"AUTHENTIC"
//}

JsonConvert 来自 Newtonsoft.Json 库。

关于c# - 如何将字符串转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53605408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com