【问题标题】:convert json string to c# list of objects (string comes from request as NULL)将 json 字符串转换为 c# 对象列表(字符串来自请求为 NULL)
【发布时间】:2015-08-11 16:37:37
【问题描述】:

我有以下代码将 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> rest_all_data { get; set; }
        }

这里是主要功能:

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

问题是当我使用这样的 json 字符串发出 http 请求时:

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

AddRestaurantMultiple 函数总是给我 null...我做错了什么??

【问题讨论】:

  • “它总是给我一个空值”是什么意思?这是非常不清楚的。如果您可以提供一个简短但完整的程序来演示该问题,这将有所帮助,最好使用惯用的 .NET 命名...
  • 如何“调用”包含AddRestaurantMultiple 函数的类?这是对 JSON 还是服务器端的客户端请求?
  • 我正在使用 fiddler 来生成请求......我的意思是当我向 AddRestaurantMultiple 函数的输入发送请求时,resaurant 类中的 resaurant 字符串始终为 NULL

标签: c# asp.net json web-services


【解决方案1】:

你的模型应该是

public class Restaurant
{
    public string RestaurantName { get; set; }
    public string CategoryName { get; set; }
    public string FourSquareID { get; set; }
}

public class rest_collection
{
    public List<Restaurant> restaurants { get; set; }
}

var result = new JavaScriptSerializer().Deserialize<rest_collection>(yourjson);

【讨论】:

  • 问题是当我使用 fiddler 进行 http 请求时...AddRestaurantMultiple 中的 json 字符串总是为 null
  • @Abdallah 鉴于您的 json 上述代码工作正常。我不知道你在用 fiddler 做什么/如何。
  • 这是我使用 fiddler 发送的消息....{"restaurants:[{"RestaurantName":"a","CategoryName":"b","FourSquareID":"c"},{"RestaurantName":"d","CategoryName":"e","FourSquareID":"f"}]}
  • @Abdallah 我不知道您的服务器、它的 API 以及它期望作为其方法的输入的内容。所以我不知道你在做什么......
猜你喜欢
  • 2014-04-07
  • 1970-01-01
  • 2020-09-22
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
相关资源
最近更新 更多