将JSON字符串转换为C#对象列表(字符串来自请求,值为NULL)

23 浏览
0 Comments

将JSON字符串转换为C#对象列表(字符串来自请求,值为NULL)

我有以下代码来将json字符串转换为对象列表:

public class rest_all
{
    public string restaurants { get; set; } 
}
public class rest_all_data
{
    public string RestaurantName { get; set; }
    public string CategoryName { get; set; }
    public string FourSquareID { get; set; } 
}
public class rest_collection 
{
    public IEnumerable rest_all_data { get; set; }
}

以下是主函数:

public void AddRestaurantMultiple (rest_all rest_all)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    rest_collection collection = serializer.Deserialize(rest_all.restaurants);
}

问题是,当我使用以下json字符串进行http请求时:

{"restaurants" : [{"RestaurantName":"a","CategoryName":"b","FourSquareID":"c"},{"RestaurantName":"d","CategoryName":"e","FourSquareID":"f"}]}

它总是在AddRestaurantMultiple函数中返回null...我做错了什么?

0
0 Comments

问题出现的原因是在使用Fiddler进行HTTP请求时,发送的JSON字符串总是为空。解决方法是检查服务器的API和方法所期望的输入,并确保发送的JSON字符串与其匹配。

在这个问题中,作者提供了解决方法的代码示例。首先,需要定义两个类:Restaurant和rest_collection。Restaurant类具有三个属性:RestaurantName、CategoryName和FourSquareID。rest_collection类具有一个名为restaurants的属性,其类型为Restaurant的列表。

然后,可以使用JavaScriptSerializer类的Deserialize方法将接收到的JSON字符串转换为rest_collection对象。代码示例如下:

var result = new JavaScriptSerializer().Deserialize(yourjson);

请注意,这里的yourjson是接收到的JSON字符串。

然而,作者指出不清楚问题所在,因为不清楚在使用Fiddler时你是如何操作的。作者建议检查服务器的API和方法,并确保发送的JSON字符串与其期望的输入匹配。

最后,作者提到发送的JSON字符串示例是:

{"restaurants:[{"RestaurantName":"a","CategoryName":"b","FourSquareID":"c"},{"RestaurantName":"d","CategoryName":"e","FourSquareID":"f"}]}

然而,由于不清楚服务器的API和方法的期望输入是什么,因此无法提供更多的帮助。

0