提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
模拟Json发送数据实现解析与格式转换的测试程序(不使用NuGet包)
前言
最近在写模拟json格式转换的测试程序,完成后总结一下,也分享给大家。实际上json数据实现格式转换的时候有专门的库,需要通过nuget包去下载,因为涉及移植性的问题,所以带我的师父直接带我手撕代码,开发一个小的测试程序。在实现的过程中感觉整个的测试程序最重要的部分,就在于json数据的格式化与解析。
JSON格式的解析与转换
1.Json的解析
需要先将string数据转为JSONNode 类型,再利用foreach循环去解析,具体见下方Json格式的转换中的代码部分。
JSONNode jsonFileAuto = JSON.Parse(jsonSFileAutoReply);
FormatENQ2(jsonFileAuto);
/*
foreach (KeyValuePair<string, JSONNode> keyValue in json)
{
string key = keyValue.Key;
JSONNode value = keyValue.Value;
}
*/
只需要根据格式一层层去添加相应的符号就可以了,我在这里介绍了一个二层格式的转换方法。
2.json格式的转换
只需要根据解析后的数据一层层去添加相应的符号就可以了,我在这里介绍了一个二层格式的转换方法。
public void FormatENQ2(JSONNode json)
{
textBox.AppendText("{");
textBox.AppendText("\r\n");
int count = json.Count;
foreach (KeyValuePair<string, JSONNode> keyValue in json)
{
count--;
string key = keyValue.Key;
JSONNode value = keyValue.Value;
textBox.AppendText("\t");
textBox.AppendText("\"" + key.ToString() + "\"" + ":");
// textBox11.AppendText(String.Format("\"{0}\"", key));
textBox.AppendText("{");
textBox.AppendText("\r\n");
int count1 = value.Count;
foreach (KeyValuePair<string, JSONNode> keyValue1 in value)
{
count1--;
string key1 = keyValue1.Key;
JSONNode value1 = keyValue1.Value;
textBox.AppendText("\t\t");
textBox.AppendText("\"" + key1.ToString() + "\"" + ":");
textBox.AppendText(value1.ToString());
if (count1 != 0) { textBox.AppendText(","); }
textBox.AppendText("\r\n");
}
textBox.AppendText("\t}");
if (count != 0) { textBox.AppendText(","); }
textBox.AppendText("\r\n");
//处理键值对
}
textBox.AppendText("}");
textBox.AppendText("\r\n");
}

3万+

被折叠的 条评论
为什么被折叠?



