Error: Problem with different types of Array vs Single Cannot deserialize current JSON object

I am trying to process data from the Auspost site. Different json is returned depending on whether 1 locality is returned or many. I tried http://json2csharp.com/ or just directly paste as json classes inside Visual Studio. I know I can write a converter, but I think the answer could be much simpler.

Error: The current JSON object cannot be deserialized Question: How do I write a class that handles both types.

** First Type JSon - Multiple Locations **

{
  "localities":{
     "locality":[
        {
           "category":"Post Office Boxes",
           "id":618,
           "location":"NORTH SYDNEY",
           "postcode":2055,
           "state":"NSW"
        },
        {
           "category":"Delivery Area",
           "id":512,
           "latitude":-33.8877655,
           "location":"THE UNIVERSITY OF SYDNEY",
           "longitude":151.1883894,
           "postcode":2006,
           "state":"NSW"
        },
        {
           "category":"Post Office Boxes",
           "id":447,
           "location":"UNSW SYDNEY",
           "postcode":1466,
           "state":"NSW"
        }
     ]
  }
}

      

** First class type **

public class Locality
{
   public string category { get; set; }
   public int id { get; set; }
   public string location { get; set; }
   public int postcode { get; set; }
   public string state { get; set; }
   public double? latitude { get; set; }
   public double? longitude { get; set; }
}

public class Localities
{
    public List<Locality> locality { get; set; }
}

public class RootObject
{
    public Localities localities { get; set; }
}

      

** Second type - Single locality **

{
  "localities":{
     "locality":{
        "category":"Delivery Area",
        "id":728,
        "latitude":-33.732122,
        "location":"COLLAROY BEACH",
        "longitude":151.301232,
        "postcode":2097,
        "state":"NSW"
     }
  }
}

      

** Second class type **

public class Locality
{
   public string category { get; set; }
   public int id { get; set; }
   public double latitude { get; set; }
   public string location { get; set; }
   public double longitude { get; set; }
   public int postcode { get; set; }
   public string state { get; set; }
}

public class Localities
{
   public Locality locality { get; set; }
}

public class RootObject
{
   public Localities localities { get; set; }
}

      

+3


source to share





All Articles