我正在使用下面的代码从服务器解析JSON响应。这有点慢。我想知道我是否应该使用JsonTextWriter作为替代方案?
我如何使用JsonTextWriter实现这个?
string responseString = string.Empty;
Uri uri = new Uri ("http://localhost/complex-json.json");
HttpWebRequest request = new HttpWebRequest (uri);
request.Method = "GET";
HttpWebResponse response = request.GetResponse () as HttpWebResponse;
using (StreamReader sr = new StreamReader(response.GetResponseStream())) {
responseString = sr.ReadToEnd ();
}
response.Close ();
JObject obj = JObject.Parse (responseString);
JArray a = (JArray)obj["questions"];
IList<question> questions = a.ToObject<IList<question>>();
for (int i = 0; i < a.Count; i++) {
Console.WriteLine(questions[0].answer_count);
}
答案 0 :(得分:0)
System.Web.Extensions.dll有一个JavaScriptSerializer
。我使用以下2种扩展方法来序列化和反序列化:
public static T JsonDeserialize<T>(this string json)
{
return new JavaScriptSerializer().Deserialize<T>(json);
}
public static string ToJson<T>(this T item)
{
return new JavaScriptSerializer().Serialize(item);
}
希望这有帮助。