3

I am trying to handle data from Auspost site. Different json is returned depending whether 1 locality is returned or Many. I tried http://json2csharp.com/ or just straight paste as json classes inside Visual Studio. I know I could write a converter - but I think the answer might be a lot simpler.

Error: Cannot deserialize the current JSON object Question: How can I write a class that handles both types.

** First Type JSon - Multiple localities **

{
  "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 Type Class **

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 Type Class **

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; }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Martin Thompson
  • 3,415
  • 10
  • 38
  • 62
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Jun 17 '15 at 01:13

0 Answers0