JsonConvert.返回空对象

本文关键字:对象 返回 JsonConvert | 更新日期: 2023-09-27 18:19:06

下面的代码尝试读取一些json并填充一个对象:

public Response ParseObject(string Json)
    {

        Response response = new Response();
        JsonConvert.PopulateObject(Json, response);
        return 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)是空的,例如(response)。Id为空,其他属性也为空)。

我猜我需要传递一些JsonSerializerSettings,但我找不到教程在任何地方?

JsonConvert.返回空对象

您可能需要检查Json字符串。当我用下面的设置运行代码时,我得到了Response对象中的值。

        var s = "{ '"id'":'"2'" , '"name'":'"Doe'" }";
        Response response = ParseObject(s); 

响应尝试使用上面的。这是为了从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);