以下代码尝试读取一些json并填充对象:
public Response ParseObject(string Json)
{
Response response = new Response();
JsonConvert.PopulateObject(Json, response);
return response;
}
这是Response对象:
public class Response
{
public string id { get; set; }
public string name { get; set; }
public string description { get; set; }
public string status { get; set; }
public string incorporationDate { get; set; }
public string latestAnnualReturnDate { get; set; }
public string latestAccountsDate { get; set; }
public string companyType { get; set; }
public string accountsType { get; set; }
不幸的是,对象(响应)是空的,即(response.id与所有其他属性一样为空)。
我猜我需要传递一些 JsonSerializerSettings ,但我找不到任何教程?
答案 0 :(得分:1)
您可能想要检查您的Json字符串。当我使用下面的设置运行你的代码时,我得到了Response对象中的值。
var s = "{ \"id\":\"2\" , \"name\":\"Doe\" }";
Response response = ParseObject(s);
答案 1 :(得分:0)
回复尝试使用上述内容。这是从HttpContext
Stream dataStream = context.Request.InputStream;
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Response data =(Response )json_serializer.DeserializeObject(responseFromServer);
在您的情况下,您可以使用
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Response data =(Response )json_serializer.DeserializeObject(Json);