1

I have a JSON return as below.

   {
    "id": 100,
    "name": "employer 100",
    "externalId": "100-100",
    "networkId": 1000,
    "address": {
        "street-address": "1230 Main Street",
        "locality": "Vancouver",
        "postal-code": "V6B 5N2",
        "region": "BC",
        "country-name": "CA"
    }
   }

So I created class to deserialize the above json.

    public class Employer
        {
            public int id { get; set; }
            public string name { get; set; }
            public string externalId { get; set; }
            public int networkId { get; set; }
            public Address address { get; set; }
        }
    public class Address
        {
            public string street_address { get; set; }
            public string locality { get; set; }
            public string postal_code { get; set; }
            public string region { get; set; }
            public string country_name { get; set; }
        }
var response = _client.Execute(req); 
return _jsonDeserializer.Deserialize <Employer> (response);

But I could not get street-address, postal-code and country-name from Json string. I think because of Json output keys contain ""-"" (As result of that I'm getting null).

So how could I resolve my issue ?

dbc
  • 104,963
  • 20
  • 228
  • 340
Gayan
  • 1,425
  • 4
  • 21
  • 41

2 Answers2

5

Use the DeserializeAs attribute on your properties:

[DeserializeAs(Name = "postal-code")]
public string postal_code { get; set; }

This allows you to set the same of the property in the json that maps to the property in your class, allowing the property to have a different name to the son.

https://github.com/restsharp/RestSharp/wiki/Deserialization

JimBobBennett
  • 2,149
  • 14
  • 11
1

If you're using JSON.net, use attributes on your properties to specify the names that they should match up to:

public class Employer
{
    public int id { get; set; }
    public string name { get; set; }
    public string externalId { get; set; }
    public int networkId { get; set; }
    public Address address { get; set; }
}
public class Address
{

    [JsonProperty("street-address")]
    public string street_address { get; set; }
    public string locality { get; set; }
    [JsonProperty("postal-code")]
    public string postal_code { get; set; }
    public string region { get; set; }
    [JsonProperty("country-name")]
    public string country_name { get; set; }
}
Whit Waldo
  • 4,806
  • 4
  • 48
  • 70
  • I dont think this gonna be work hence street-address as street_address – Gayan Apr 13 '16 at 21:05
  • @GayanJ Easily solved, just change the string within the quotes. I've updated my answer to reflect the change to use a dash instead of an underline. – Whit Waldo Apr 14 '16 at 01:27