我以这种格式从源中获取数据:
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"
}
谢谢。
答案 0 :(得分:4)
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库。
答案 1 :(得分:1)
因此,您必须首先剖析输入字符串,然后从中创建一些JSON。第一个任务可能是正则表达式的任务,由于所需的JSON似乎只有字符串值,因此第二个任务可以由正则表达式完成:
var s = "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";
var regex = new Regex(@"(?<n>\w+)=(?<v>\w+)");
var json = "{" + regex.Replace(s, m => string.Format("\"{0}\":\"{1}\"", m.Groups["n"].Value, m.Groups["v"])) + "}";
答案 2 :(得分:0)
将Newtonsoft.Json库用于sonConvert.SerializeObject()