使用开源的类库Newtonsoft.Json(下载地址http://json.codeplex.com/)。下载后加入工程就能用。通常可以使用JObject, JsonReader, JsonWriter处理。这种方式最通用,也最灵活,可以随时修改不爽的地方。
(1)使用JsonReader读Json字符串:
string jsonText = @"{""input"" : ""value"", ""output"" : ""result""}"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); while (reader.Read()) { Console.WriteLine(reader.TokenType + " " + reader.ValueType + " " + reader.Value); }
.
(2)使用JsonWriter写字符串:
StringWriter sw = new StringWriter(); JsonWriter writer = new JsonTextWriter(sw); writer.WriteStartObject(); writer.WritePropertyName("input"); writer.WriteValue("value"); writer.WritePropertyName("output"); writer.WriteValue("result"); writer.WriteEndObject(); writer.Flush(); string jsonText = sw.GetStringBuilder().ToString(); Console.WriteLine(jsonText);
(3)使用JObject读写字符串:
JObject jo = JObject.Parse(jsonText); string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray(); 或者 var aa = jo["data"]["token"];
(4)使用DeserializeObject转换成对象
string jsonStr="{"fundcode":"163407","name":"兴全沪深300指数(LOF)","jzrq":"2018-02-28","dwjz":"1.8433","gsz":"1.8544","gszzl":"0.60","gztime":"2018-03-01 15:00"}"; TTApiResult obj = (TTApiResult)JsonConvert.DeserializeObject<TTApiResult>(jsonStr);