Link to home
Start Free TrialLog in
Avatar of ITsolutionWizard
ITsolutionWizardFlag for United States of America

asked on

C# read json

1. I used mapquest api to generate json string.
2. then I go to https://json2csharp.com/json-to-csharp to generate the c# class below
3. Then I write the c# code test() below.
4. the json result is generated correctly from MapQuest API.

My question is:
1. I try to get myDeserializedClass.lat and myDeserializedClass.lng and return 0. It is supposed to return some values. Can you check how to fix it?





 public static string test()
        {
            string url = "https://www.mapquestapi.com/geocoding/v1/address?key=WZfUGAtdasdfasdffbgAnG9Ebq1HsD2c7X2w5ngN&inFormat=kvp&outFormat=json&location=Denver%2C+CO&thumbMaps=false";
            String result;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            result = readStream.ReadToEnd();
            Domain.MaqQuest.LatLng myDeserializedClass = JsonConvert.DeserializeObject<Domain.MaqQuest.LatLng>(result);                        
            response.Close();
            readStream.Close();
            return "Return Value: " + myDeserializedClass.lat + " " +  myDeserializedClass.lng;
        }

Open in new window







// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
    public class Copyright    {
        public string text { get; set; }
        public string imageUrl { get; set; }
        public string imageAltText { get; set; }
    }


    public class Info    {
        public int statuscode { get; set; }
        public Copyright copyright { get; set; }
        public List<object> messages { get; set; }
    }


    public class Options    {
        public int maxResults { get; set; }
        public bool thumbMaps { get; set; }
        public bool ignoreLatLngInput { get; set; }
    }


    public class ProvidedLocation    {
        public string location { get; set; }
    }


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


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


    public class Location    {
        public string street { get; set; }
        public string adminArea6 { get; set; }
        public string adminArea6Type { get; set; }
        public string adminArea5 { get; set; }
        public string adminArea5Type { get; set; }
        public string adminArea4 { get; set; }
        public string adminArea4Type { get; set; }
        public string adminArea3 { get; set; }
        public string adminArea3Type { get; set; }
        public string adminArea1 { get; set; }
        public string adminArea1Type { get; set; }
        public string postalCode { get; set; }
        public string geocodeQualityCode { get; set; }
        public string geocodeQuality { get; set; }
        public bool dragPoint { get; set; }
        public string sideOfStreet { get; set; }
        public string linkId { get; set; }
        public string unknownInput { get; set; }
        public string type { get; set; }
        public LatLng latLng { get; set; }
        public DisplayLatLng displayLatLng { get; set; }
    }


    public class Result    {
        public ProvidedLocation providedLocation { get; set; }
        public List<Location> locations { get; set; }
    }


    public class Root    {
        public Info info { get; set; }
        public Options options { get; set; }
        public List<Result> results { get; set; }
    }


Open in new window


{"info":{"statuscode":0,"copyright":{"text":"\u00A9 2021 MapQuest, Inc.","imageUrl":"http://api.mqcdn.com/res/mqlogo.gif","imageAltText":"\u00A9 2021 MapQuest, Inc."},"messages":[]},"options":{"maxResults":-1,"thumbMaps":false,"ignoreLatLngInput":false},"results":[{"providedLocation":{"location":"Denver, CO"},"locations":[{"street":"","adminArea6":"","adminArea6Type":"Neighborhood","adminArea5":"Denver","adminArea5Type":"City","adminArea4":"Denver County","adminArea4Type":"County","adminArea3":"CO","adminArea3Type":"State","adminArea1":"US","adminArea1Type":"Country","postalCode":"","geocodeQualityCode":"A5XAX","geocodeQuality":"CITY","dragPoint":false,"sideOfStreet":"N","linkId":"282041090","unknownInput":"","type":"s","latLng":{"lat":39.738453,"lng":-104.984853},"displayLatLng":{"lat":39.738453,"lng":-104.984853}},{"street":"","adminArea6":"","adminArea6Type":"Neighborhood","adminArea5":"","adminArea5Type":"City","adminArea4":"Denver County","adminArea4Type":"County","adminArea3":"CO","adminArea3Type":"State","adminArea1":"US","adminArea1Type":"Country","postalCode":"","geocodeQualityCode":"A4XAX","geocodeQuality":"COUNTY","dragPoint":false,"sideOfStreet":"N","linkId":"282932003","unknownInput":"","type":"s","latLng":{"lat":39.738453,"lng":-104.984853},"displayLatLng":{"lat":39.738453,"lng":-104.984853}}]}]}

Open in new window


Avatar of it_saige
it_saige
Flag of United States of America image

You need to deserialize based on the root class; e.g. -
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result

Open in new window

Proof of concept -
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace EE_Q29205423
{
    class Program
    {
        static void Main(string[] args)
        {
            var response = GetMapQuestResponse();
            if (response != default(MapQuestResponse))
            {
                foreach (var result in response.Results)
                {
                    foreach (var location in result.Locations)
                    {
                        Console.WriteLine($"Location: {result.ProvidedLocation.Location}; Latitude: {location.LatLng.Lat}; Longitude: {location.LatLng.Lng}");
                    }
                }
            }

            Console.ReadLine();
        }

        static MapQuestResponse GetMapQuestResponse()
        {
            // This is how I would re-write your method
            //var result = default(MapQuestResponse);
            //var data = default(string);
            //var url = "https://www.mapquestapi.com/geocoding/v1/address?key=<yourSecretKey>&inFormat=kvp&outFormat=json&location=Denver%2C+CO&thumbMaps=false";

            //try
            //{
            //    var request = (HttpWebRequest)WebRequest.Create(url);
            //    request.MaximumAutomaticRedirections = 4;
            //    request.MaximumResponseHeadersLength = 4;
            //    request.Credentials = CredentialCache.DefaultCredentials;
            //    var response = (HttpWebResponse)request.GetResponse();
            //    using (var stream = response.GetResponseStream())
            //    {
            //        using (var reader = new StreamReader(stream, Encoding.UTF8))
            //        {
            //            data = reader.ReadToEnd();
            //        }
            //    }

            //    result = JsonConvert.DeserializeObject<MapQuestResponse>(data);
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine($"Exception reported - {ex}");
            //    result = default(MapQuestResponse);
            //}

            // For now we will mock the data based on your provided response string
            var data = "{'info':{'statuscode':0,'copyright':{'text':'\u00A9 2021 MapQuest, Inc.','imageUrl':'http://api.mqcdn.com/res/mqlogo.gif','imageAltText':'\u00A9 2021 MapQuest, Inc.'},'messages':[]},'options':{'maxResults':-1,'thumbMaps':false,'ignoreLatLngInput':false},'results':[{'providedLocation':{'location':'Denver, CO'},'locations':[{'street':'','adminArea6':'','adminArea6Type':'Neighborhood','adminArea5':'Denver','adminArea5Type':'City','adminArea4':'Denver County','adminArea4Type':'County','adminArea3':'CO','adminArea3Type':'State','adminArea1':'US','adminArea1Type':'Country','postalCode':'','geocodeQualityCode':'A5XAX','geocodeQuality':'CITY','dragPoint':false,'sideOfStreet':'N','linkId':'282041090','unknownInput':'','type':'s','latLng':{'lat':39.738453,'lng':-104.984853},'displayLatLng':{'lat':39.738453,'lng':-104.984853}},{'street':'','adminArea6':'','adminArea6Type':'Neighborhood','adminArea5':'','adminArea5Type':'City','adminArea4':'Denver County','adminArea4Type':'County','adminArea3':'CO','adminArea3Type':'State','adminArea1':'US','adminArea1Type':'Country','postalCode':'','geocodeQualityCode':'A4XAX','geocodeQuality':'COUNTY','dragPoint':false,'sideOfStreet':'N','linkId':'282932003','unknownInput':'','type':'s','latLng':{'lat':39.738453,'lng':-104.984853},'displayLatLng':{'lat':39.738453,'lng':-104.984853}}]}]}";
            var result = JsonConvert.DeserializeObject<MapQuestResponse>(data);

            return result;
        }
    }

    public class MapQuestResponse
    {
        public Info Info { get; set; }
        public Options Options { get; set; }
        public List<Result> Results { get; set; }
    }

    public class Info
    {
        public int StatusCode { get; set; }
        public Copyright Copyright { get; set; }
        public List<object> Messages { get; set; }
    }

    public class Copyright
    {
        public string Text { get; set; }
        public string ImageUrl { get; set; }
        public string ImageAltText { get; set; }
    }

    public class Options
    {
        public int MaxResults { get; set; }
        public bool ThumbMaps { get; set; }
        public bool IgnoreLatLngInput { get; set; }
    }

    public class Result
    {
        public ProvidedLocation ProvidedLocation { get; set; }
        public List<Location> Locations { get; set; }
    }

    public class ProvidedLocation
    {
        public string Location { get; set; }
    }

    public class Location
    {
        public string Street { get; set; }
        public string AdminArea6 { get; set; }
        public string AdminArea6Type { get; set; }
        public string AdminArea5 { get; set; }
        public string AdminArea5Type { get; set; }
        public string AdminArea4 { get; set; }
        public string AdminArea4Type { get; set; }
        public string AdminArea3 { get; set; }
        public string AdminArea3Type { get; set; }
        public string AdminArea1 { get; set; }
        public string AdminArea1Type { get; set; }
        public string PostalCode { get; set; }
        public string GeocodeQualityCode { get; set; }
        public string GeocodeQuality { get; set; }
        public bool DragPoint { get; set; }
        public string SideOfStreet { get; set; }
        public string LinkId { get; set; }
        public string UnknownInput { get; set; }
        public string Type { get; set; }
        public LatLng LatLng { get; set; }
        public DisplayLatLng DisplayLatLng { get; set; }
    }

    public class LatLng
    {
        public double Lat { get; set; }
        public double Lng { get; set; }
    }

    public class DisplayLatLng
    {
        public double Lat { get; set; }
        public double Lng { get; set; }
    }
}

Open in new window

Provides the following output -
User generated image
HTH,

-saige-
Avatar of ITsolutionWizard

ASKER

thank you. it works. You are very smart. I just want to learn about default(MapQuestResponse).
What & why use "default"?
ASKER CERTIFIED SOLUTION
Avatar of it_saige
it_saige
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial