c#json json.net解析到课堂

时间:2016-06-21 07:16:54

标签: c# json

有一段时间我的代码有问题。 尝试使用json从API检索数据,但在尝试解析json并将其发送到类时,我收到空字符串。

json数据看起来像这样

{"Wynik":{"Token":"String","DataCzasWaznosci":"\/Date(-62135596800000-0000)\/"}

...这是我的代码:

public void post()
{
    Autoryzacja_zaloguj a_zaloguj = new Autoryzacja_zaloguj();
    string url = a_zaloguj.Link;
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);


    byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(a_zaloguj.Json);
    req.Method = "POST";
    req.ContentType = "application/json";
    req.ContentLength = requestBytes.Length;
    Stream requestStream = req.GetRequestStream();
    requestStream.Write(requestBytes, 0, requestBytes.Length);
    requestStream.Close();

    HttpWebResponse res = (HttpWebResponse)req.GetResponse();
    StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);

    string backstr = sr.ReadToEnd();
    dynamic d = JObject.Parse(backstr);
    var wynik = d.Wynik;
    string token = wynik.Token;
    DateTime data = wynik.DataCzasWaznosci;

    Wyniki wyniki = new Wyniki();
    wyniki.test = token;

    sr.Close();
    res.Close();
}

public class Wyniki
{
    public string test { get; internal set; }
}

1 个答案:

答案 0 :(得分:0)

您可以使用Newtosoft nugget包进行此类解析 http://www.newtonsoft.com/json

public class Wynik
{
    public string Token { get; set; }
    public DateTime DataCzasWaznosci { get; set; }
}

/*Deserialization part */
string backstr = sr.ReadToEnd();
Wynikm = JsonConvert.DeserializeObject<Wynik>(backstr);