简体   繁体   中英

Geocoding REST call C# Parsing JSON

I'm struggling to pick up the data returned from the Geocoding REST call below (I've removed my app_id and app_code so you cannot run the url as it is below):

https://geocoder.api.here.com/6.2/geocode.json?app_id=[MY APP ID]&app_code=[MY APP CODE]&searchtext=chester

An example reponse can be found here:

https://developer.here.com/documentation/geocoder/topics/quick-start-geocode.html

I know it returns results but I cannot seem to get the results through to my C# application, I don't know if I'm building the class system incorrectly or whether there's something else I'm doing wrong. I've built an application reading the places api with no problem before but this one seems different somehow.

The call returns with a status of OK:

public void GeoCode()
    {
        // BUILD INITIAL STRING BASED ON PARAMETERS
        string url = "https://geocoder.api.here.com/6.2/geocode.json?app_id=gpZ1Ym7rwuXs6Xj1TsD8&app_code=4UXmaGFTe30LttFgOY7iqQ&searchtext=" + tbLoc.text;
        // RUN THE ASYNCRONOUS COMMAND (I THINK)
        StartCoroutine(GetText(url));
    }

    IEnumerator GetText(string url)
    {
        // CREATE WEB REQUEST WITH SPECIFIED URL
        UnityWebRequest www = UnityWebRequest.Get(url);
        // RETURN RESULTS FROM ASYNC COMMAND
        yield return www.SendWebRequest();
        // PARSE JSON RESPONSE
        RootObject RootObject = JsonUtility.FromJson<RootObject>(www.downloadHandler.text);
        // IF 200 (STATUS OKAY) GATHER RESULTS, ELSE RETURN ERROR
        if (www.responseCode == 200)
        {
            BuildArray(RootObject);
        }
        else
        {
            Debug.Log("Call Failed With Error: " + www.responseCode.ToString());
        }
    }

    private void BuildArray(RootObject RootObject)
    {
        print(RootObject.Response.View[0].Result[0].Location.Address.Label);
    }

It attempts to run the BuildArray function but this returns a null reference. (I'm just using the NextPageInformation as the most basic option to test)

Below is the class structure I have built to deal with the JSON:

    public class Address
    {
        public string Label { get; set; }
    }

    public class Location
    {
        public Address Address { get; set; }
    }

    public class Result
    {
        public Location Location { get; set; }
    }

    public class View
    {
        public List<Result> Result { get; set; }
    }

    public class Response
    {
        public List<View> View { get; set; }
    }

    public class RootObject
    {
        public Response Response { get; set; }
    }

Can someone please help? Thank you

I personally had problems parsing nested json objects with JsonUtility. So I switched to Newtonsoft Json and it works really well. In your case you need to mark the classes as serialized using [Serializable] see here

[Serializable] 
public class Address
    {
        public string Label;
    }

If you want to parse only one key value pair from json then creating class structure will tedious job for you.

Instead of creating class structure you can Querying a json with Newtonsoft .

  1. Parse your json.
  2. Querying your parsed json to retrieve Label value.

//1
JToken jToken = JToken.Parse(jsonString);

//2
string label = jToken["Response"]["View"][0]["Result"][0]["Location"]["Address"]["Label"].ToObject<string>();

Console.WriteLine(label);

Console.ReadLine();

Output: (from your sample json provided in link)

在此处输入图片说明

Note: You need to install newtonsoft.json package from nuget and add below namespace to your program.

using Newtonsoft.Json.Linq;

Edit:

If you want parsed your full json then first create a class structure like below

public class MetaInfo
{
    public DateTime Timestamp { get; set; }
}

public class MatchQuality
{
    public int City { get; set; }
    public List<double> Street { get; set; }
    public int HouseNumber { get; set; }
}

public class DisplayPosition
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

public class NavigationPosition
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

public class TopLeft
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

public class BottomRight
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

public class MapView
{
    public TopLeft TopLeft { get; set; }
    public BottomRight BottomRight { get; set; }
}

public class AdditionalData
{
    public string value { get; set; }
    public string key { get; set; }
}

public class Address
{
    public string Label { get; set; }
    public string Country { get; set; }
    public string State { get; set; }
    public string County { get; set; }
    public string City { get; set; }
    public string District { get; set; }
    public string Street { get; set; }
    public string HouseNumber { get; set; }
    public string PostalCode { get; set; }
    public List<AdditionalData> AdditionalData { get; set; }
}

public class Location
{
    public string LocationId { get; set; }
    public string LocationType { get; set; }
    public DisplayPosition DisplayPosition { get; set; }
    public List<NavigationPosition> NavigationPosition { get; set; }
    public MapView MapView { get; set; }
    public Address Address { get; set; }
}

public class Result
{
    public int Relevance { get; set; }
    public string MatchLevel { get; set; }
    public MatchQuality MatchQuality { get; set; }
    public string MatchType { get; set; }
    public Location Location { get; set; }
}

public class View
{
    public string _type { get; set; }
    public int ViewId { get; set; }
    public List<Result> Result { get; set; }
}

public class Response
{
    public MetaInfo MetaInfo { get; set; }
    public List<View> View { get; set; }
}

public class RootObject
{
    public Response Response { get; set; }
}

And then you can deserialized your json like.

RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(jsonString);

Note: You need to add below namespace to your program.

using Newtonsoft.Json;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM