wp8 自定义Json数据内容

LZ在 http://blog.csdn.net/irenemay/article/details/12760751 说明了使用.Net自带的方法实现Json与字串的转换,但在实际使用中,可能协议本身并没有自定Json的Key值,导致我们不能确定所需的[DataMember],下面的方法实现了使用自定义Key到字串之间的转换。

 

class Json
    {
        public static StringBuilder strBuild = new StringBuilder("");//存储<Key,Value>转换成的Json

        public static Dictionary<string, string> dict;//存储Json转换成的<Key,Value>
        
        //加入Json数据格式的头 '{'
        public static void AddHead()
        {
            strBuild.Append("{");
        }
     
        //添加<Key,Value>
        public static void AddToJson(string istr, int i)
        {
            strBuild.Append("\"" + istr + "\"" + ":" + i.ToString());
        }
	public static void AddToJson(string istr, string str)
        {
            strBuild.Append("\"" + istr +"\"" + ":" + "\"" + str + "\"");
        }

        //添加','
        public static void AddComma()
        {
            strBuild.Append(",");
        }
   
        //添加Json数据格式的末尾 '}'
        public static void AddEnd()
        {
            strBuild.Append("}");
        }

        //解析Json数据到字符串
        public static void SovJson(string istr)
        {
            //去头去尾 '{' 和 '}'
            StringBuilder strbb = new StringBuilder(istr);
            
            strbb.Remove(0, 1);
            strbb.Remove(strbb.Length - 1, 1);

            //按 ',' 分开
            string[] strC = strbb.ToString().Split(new char[] { ',' });
            string[][] strCmd = new string[strC.Length][];

            //按 ':' 分开
            for (int i = 0; i < strC.Length; i++)
            {
                strCmd[i] = strC[i].Split(new char[] { ':' });
            }

            //添加数据
            dict = new Dictionary<string, string>();
            for (int i = 0; i < strC.Length; i++)
            {
                StringBuilder temp1 = new StringBuilder(strCmd[i][0]);
                temp1.Remove(0, 1);
                temp1.Remove(temp1.Length - 1, 1);
                strCmd[i][0] = temp1.ToString();
                int xtemp;
                if (!int.TryParse(strCmd[i][1], out xtemp))
                {
                    temp1 = new StringBuilder(strCmd[i][1]);
                    temp1.Remove(0, 1);
                    temp1.Remove(temp1.Length - 1, 1);
                    strCmd[i][1] = temp1.ToString();
                }

                dict.Add(strCmd[i][0], strCmd[i][1].ToString());
            }
        }
   
        //清空strBuild,为下一次解析做准备
        public static void Clear()
        {
            strBuild.Clear();
            dict = null;
        }
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值