我有一个 json 格式的字符串
{
"code": 0,
"message": "success",
"data": [
{
"data": 10,
"total": 1000
}
],
"page": {
"page": 1,
"per_page": 200,
}
}
我只是尝试通过以下代码将其转换为json,
public class Invoice
{
public int data {get; set;}
public int total { get; set; }
}
public class Page
{
public int page { get; set; }
public int per_page { get; set; }
}
public class RootObject
{
public int code { get; set; }
public string message { get; set; }
public List<Lisst> Lisst{ get; set; }
public Page Page{ get; set; }
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(GotResponse), request);
}
private void GotResponse(IAsyncResult asyncResult)
{
try
{
string data;
HttpWebRequest myhttpwebrequest = (HttpWebRequest)asyncResult.AsyncState; ;
using (HttpWebResponse response = (HttpWebResponse)myhttpwebrequest.EndGetResponse(asyncResult))
{
System.IO.Stream responseStream = response.GetResponseStream();
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
}
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(data);
});
var myObjects = JsonConvert.DeserializeObject<RootObject>(data);
}
catch (Exception e)
{
var we = e.InnerException as WebException;
System.Diagnostics.Debug.WriteLine("error : "+ we);
if (we != null)
{
var resp = we.Response as HttpWebResponse;
var code = resp.StatusCode;
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Bye");
});
}
else
throw;
}
当我运行此代码时,预期的输出存储为数据中的字符串,但在运行该行时
var myObjects = JsonConvert.DeserializeObject<RootObject>(data);
我收到一条错误消息,指出 Newtonsoft.Json.DLL 中发生了“System.FormatException”类型的异常,但未在用户代码中处理...这是存储为键值对的正确方法吗?