2015-07-02 133 views
0

我不能反序列化如下回應: 我的JSON是反序列化JSON響應到C#

json is 
{ 
    "disclaimer": "Exchange rates/", 
    "license": "Data sourced from various providers", 
    "timestamp": 1435813262, 
    "base": "USD", 
    "rates": { 
    "AED": 3.672973, 
    "AFN": 60.150001, 
    "ALL": 126.7792, 
    "AMD": 472.46, 
    "ANG": 1.78875, 
    "AOA": 121.253666, 
    "ARS": 9.095239, 
    "AUD": 1.307011, 
    "AWG": 1.793333, 
    "AZN": 1.04955, 
} 
} 

控制器是:

[HttpPost] 
public ActionResult Index(Test1 values) 
{ 

    string appid = values.apikey; 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://openexchangerates.org//api/latest.json?app_id=5db2fa81c8174a839756eb4d5a4a5e05"); 

    request.Method = "POST"; 

    using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream(), ASCIIEncoding.ASCII)) 
    { 
     streamWriter.Write(appid1); 
     streamWriter.Close(); 
    } 

    string responseText = String.Empty; 

    if (request.Headers.Count > 0) 
    { 

     using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream())) 
     { 
      responseText = sr.ReadToEnd(); 

     } 
    } 

    var myObject = JsonConvert.DeserializeObject(responseText); 
} 
+1

可能重複[反序列化JSON與C#(HTTP: //stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp) –

回答

5

按照此處:http://www.newtonsoft.com/json/help/html/DeserializeObject.htm

不要忘了爲你的反序列化對象聲明一個類。它應該包含json對象已有的字段或其中的一些字段。

我不知道,如果你的代碼完全工作,除了反序列化的過程,但下面有個代碼示例爲你讓你明白我的意思:

class MyClass 
{ 
    public string disclaimer { get; set; } 
    public string license { get; set; } 
    public string timestamp { get; set; } 
    ... 
} 

[HttpPost] 
public ActionResult Index(Test1 values) 
{ 
    ... 
    var myObject = JsonConvert.DeserializeObject<MyClass>(responseText); 
    ... 
}