簡體   English   中英

將JSON反序列化為C#對象列表

[英]Deserializing a JSON into a C# List of Objects

我正在嘗試從Google Places API反序列化JSON。 我的自定義類設置如下,我的代碼如下所示。 運行時,我的程序未引發任何錯誤,但我的places對象為null。

class PlacesDictionary
{

    public void placesDictionary()
    { }

    public Places GetPlaces()
    {
        Places places = new Places();

        string apiKey = "I have an apiKey";
        string googleUrl;
        googleUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=43.038902,-87.906474&radius=500&type=restaurant&name=cruise&key=" + apiKey;

        WebRequest request = WebRequest.Create(googleUrl);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        WebResponse response = request.GetResponse();
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        places = JsonConvert.DeserializeObject<Places>(responseFromServer);

        Console.WriteLine(responseFromServer);
        Console.ReadLine();
        reader.Close();
        dataStream.Close();
        response.Close();

        return places;
    }
}

public class Places
{
    public List<Place> places { get; set; }

    public class Place
    {
        public Geometry geometry { get; set; }
        public string icon { get; set; }
        public string id { get; set; }
        public string name { get; set; }
        public OpeningHours opening_hours { get; set; }
        public List<Photo> photos { get; set; }
        public string place_id { get; set; }
        public int price_level { get; set; }
        public double rating { get; set; }
        public string reference { get; set; }
        public string scope { get; set; }
        public List<string> types { get; set; }
        public string vicinity { get; set; }

        public class Location
        {
            public double lat { get; set; }
            public double lng { get; set; }
        }

        public class Northeast
        {
            public double lat { get; set; }
            public double lng { get; set; }
        }

        public class Southwest
        {
            public double lat { get; set; }
            public double lng { get; set; }
        }

        public class Viewport
        {
            public Northeast northeast { get; set; }
            public Southwest southwest { get; set; }
        }

        public class Geometry
        {
            public Location location { get; set; }
            public Viewport viewport { get; set; }
        }

        public class OpeningHours
        {
            public bool open_now { get; set; }
            public List<object> weekday_text { get; set; }
        }

        public class Photo
        {
            public int height { get; set; }
            public List<string> html_attributions { get; set; }
            public string photo_reference { get; set; }
            public int width { get; set; }
        }
    }
}

我認為你應該使用

List<Place> places = JsonConvert.DeserializeObject<List<Place>>(responseFromServer);

代替

places = JsonConvert.DeserializeObject<Places>(responseFromServer);

並且不要忘記刪除以下行

 Places places = new Places();

編輯:完整答案

     static void Main(string[] args)
     {
           string apiKey = "your api key";
           string googleUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=43.038902,-87.906474&radius=500&type=restaurant&name=cruise&key=" + apiKey;

            WebRequest request = WebRequest.Create(googleUrl);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            WebResponse response = request.GetResponse();
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            //StreamWriter wr = new StreamWriter("json.txt");
            //wr.WriteLine(responseFromServer);
            //wr.Flush();
            //To see what it is inside json
            Result results = JsonConvert.DeserializeObject<Result>(responseFromServer);

            Console.WriteLine(responseFromServer);
            Console.ReadLine();
            reader.Close();
            dataStream.Close();
            response.Close();

        }
    }

    public class Result
    {
        public List<HTMLAttribution> html_attributions { get; set; }
        public string next_page_token { get; set; }
        public List<Place> results { get; set; }
        public string status { get; set; }

        //Definations of Classes
        public class HTMLAttribution { } //I don't what it is. It is empty for your url.

        public class Place
        {
            public Geometry geometry { get; set; }
            public string icon { get; set; }
            public string id { get; set; }
            public string name { get; set; }
            public OpeningHours opening_hours { get; set; }
            public List<Photo> photos { get; set; }
            public string place_id { get; set; }
            public int price_level { get; set; }
            public double rating { get; set; }
            public string reference { get; set; }
            public string scope { get; set; }
            public List<string> types { get; set; }
            public string vicinity { get; set; }

            public class Geometry
            {
                public Location location { get; set; }
                public Viewport viewport { get; set; }
            }
            public class Location
            {
                public double lat { get; set; }
                public double lng { get; set; }
            }
            public class Viewport
            {
                public Northeast northeast { get; set; }
                public Southwest southwest { get; set; }
            }
            public class Northeast
            {
                public double lat { get; set; }
                public double lng { get; set; }
            }

            public class Southwest
            {
                public double lat { get; set; }
                public double lng { get; set; }
            }
            public class OpeningHours
            {
                public bool open_now { get; set; }
                public List<object> weekday_text { get; set; }
            }
            public class Photo
            {
                public int height { get; set; }
                public List<string> html_attributions { get; set; }
                public string photo_reference { get; set; }
                public int width { get; set; }
            }
        }
    }

我會嘗試一些(如果我是你的話):

刪除Places places = new Places();

替換places = JsonConvert.DeserializeObject(responseFromServer); 通過Places places = JsonConvert.DeserializeObject(responseFromServer);

並在Places類中添加默認構造函數,就像在PlacesDictionary中添加一樣。

1.只參加地方課程。

2.初始化List<Place> places=new List<Place>()

3.使用場所反序列化

places = JsonConvert.DeserializeObject<places>(responseFromServer);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM