Json序列化-内存流超时

本文关键字:超时 内存 序列化 Json | 更新日期: 2023-09-27 18:15:11

我试图将数据从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;
    }

谢谢大家的建议

Json序列化-内存流超时

//这就是你需要的

    // 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();

来自您的站点的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);

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