我通常做的是使用 C# 原生 String.Split 拆分 JSON 字符串
const string quote = "\""; //You can ignore this line if you like it just adds the "" as a constant string/char value!
string storedValue = "{"firstName":"John", "lastName":"Doe"}" //The JSON value stored either from an HTTPWebRequest or some other method!
string[] str = storedValue.Split(new string[] {quote + "firstName" + quote + ":" }, StringSplitOptions.None); //Split the JSON firstName value!
所以编译器本质上会查找“firstName”:并将 firstName 值与所有其他代码分开,但是如果您执行 str[1],它也会获取 lastName 值,所以我在发送 HTTPWebRequest 后总是这样做从目标服务器接收请求,然后拆分我想要的 ID,然后在“,”处拆分最后一次以从我想要吐出的 JSON 代码中删除姓氏!
string[] finalSplit = str.Split(new string[] { "," }, StringSplitOptions.None);
string output = finalSplit[0].ToString();
据我所知,“输出”字符串值应该等于 JSON 代码中的“约翰”值!
如果要删除引号,请使用 C# 中的 Regex.Replace()。
using System.Net.RegularExpressions; //Import C# library using this code at the top of your class or above the Namespace declaration!
Regex.Replace(output, @quotes, ""); //The 'quotes' method was declared at the top of the first code block it was that code I said you could ignore if you really wanted to!
删除引号后,最后要做的就是将输出放入标签、文本框,甚至可能是使用 System.IO.streamWriter 的文件!
另外顺便说一句,您如何从文件或通过 HTTPWebRequest 获取 JSON 代码?如果您从 HTTPWebRequest 获取 JSON 代码,我建议将代码转换为 UTF-8 以确保安全!
现在我知道有一种更正式的方法可以在 C# 中读取 JSON,但这是我的方法,它适用于我,所以如果我有一个同样有效的方法,我认为没有理由使用官方方法,但同样如此只是我的意见! :)