Json序列化 - 记忆流超时

时间:2016-10-26 18:20:08

标签: c# uwp

我试图将数据从json序列化到C#,并且每当它在内存流上抛出异常时:+ WriteTimeout' ms.WriteTimeout'抛出类型' System.InvalidOperationException'

它与XML

做同样的事情

这里的代码:

[DataContract]
public class Svatek
{
    [DataMember]
    public string date { get; set; }
    [DataMember]
    public string name { get; set; }
}

和这里的方法

    public async static Task<Svatek> GetDnesniSvatek()
    {
        var http = new HttpClient();
        var url = string.Format("http://svatky.adresa.info/json");
        var response = await http.GetAsync(url);
        var result = await response.Content.ReadAsStringAsync();

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Svatek));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
        Svatek dnesniSvatek = new Svatek();
        dnesniSvatek = (Svatek)serializer.ReadObject(ms);
        return dnesniSvatek;
    }

感谢所有建议

2 个答案:

答案 0 :(得分:0)

//这是你需要的exatcly

    // Create a request for the URL. 
    WebRequest request = WebRequest.Create(
      "http://svatky.adresa.info/json");
    // If required by the server, set the credentials.
    request.Credentials = CredentialCache.DefaultCredentials;
    // Get the response.
    WebResponse response = request.GetResponse();
    // Display the status.
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    // Get the stream containing content returned by the server.
    Stream dataStream = response.GetResponseStream();
    // Open the stream using a StreamReader for easy access.
    StreamReader reader = new StreamReader(dataStream);
    // Read the content.
    string responseFromServer = reader.ReadToEnd();
    // Display the content.

    Svatek myObjectSvatek = JsonConvert.DeserializeObject<Svatek>(responseFromServer );


    // Clean up the streams and the response.
    reader.Close();
    response.Close();

答案 1 :(得分:0)

来自您网站的json是数组。所以你的代码应反序列化为 list array

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Svatek>));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result));

var list = (List<Svatek>)serializer.ReadObject(ms);

你所有其他代码都正常工作.....