Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to map JSON to class

I make a request to an external API and get JSON data back, the data returned is in the following format:

abnCallback({
    "Abn": "53660112345",
    "AbnStatus": "Active",
    "AbnStatusEffectiveFrom": "2022-06-16",
    "Acn": "660198745",
    "AddressDate": "2022-06-16",
    "AddressPostcode": "3000",
    "AddressState": "VIC",
    "BusinessName": [],
    "EntityName": "Company name pty ltd",
    "EntityTypeCode": "PRV",
    "EntityTypeName": "Private Company",
    "Gst": "2022-06-16",
    "Message": ""
})

I’m trying to map this to a model by doing the following:

var jsonString = await response.Content.ReadAsStringAsync();
var response = JsonConvert.DeserializeObject<ABRPayloadSearchResults>(jsonString);

My model looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class ABRPayloadSearchResults
{
    public string Abn { get; set; }
    public string AbnStatus { get; set; }
    public string AbnStatusEffectiveFrom { get; set; }
    public string Acn { get; set; }
    public string AddressDate { get; set; }
    public string AddressPostcode { get; set; }
    public string AddressState { get; set; }
    public object[] BusinessName { get; set; }
    public string EntityName { get; set; }
    public string EntityTypeCode { get; set; }
    public string EntityTypeName { get; set; }
    public string Gst { get; set; }
    public string Message { get; set; }
}

The issue I have is the returned JSON has abnCallBack( at the start which is preventing the json being mapped correctly to my class, has anyone had to handle this situation before?

>Solution :

This format is called JSONP. It wraps a JSON object in a (javascript) function call, which enables a browser to download the JSON via a <script>. This can be used to circumvent cross origin policies to load JSON from other domains.

I don’t believe there is a built-in way to deserialize JSONP in C#, but you should be able to manipulate the string quite easily to remove the function name and the brackets. See e.g. How to deserialize a JSONP response (preferably with JsonTextReader and not a string)?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading