如何将字符串转换为JSON

1banez

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

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"
}

谢谢。

彼得·波哥亚维伦斯基(Petr Bogoyavlenskiy)
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库。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章