0

For Example :

For train Availability, sometimes we are getting response , applicableBerthTypes as List in case of multiple berth available such as LOWER,UPPER etc. Sometimes we are getting response as applicableBerthTypes as string in case of only one berth type is available such as SITTING.

Model class will be ,

public class BkgCfg
{
    public string acuralBooking { get; set; }
    public List<string> applicableBerthTypes { get; set; }
}

JSON Response that we are recieving from Supplier end.

LstrApidata= {"acuralBooking": "","applicableBerthTypes":["LB","MB","UB","SL","SU"]}

Working fine when am trying to deserialize above Json .

LobjBkgCfg = JsonConvert.DeserializeObject<BkgCfg>(LstrApiData);

When supplier sends json as

{
  "acuralBooking": null,
  "applicableBerthTypes":"LB"
}

getting error when am trying to deserialize above Json.

LobjBkgCfg = JsonConvert.DeserializeObject<BkgCfg>(LstrApiData);

For each and every response, i need to create two model classes , one is for "List" and another one is "string". Is it possible to create one property that accept list as well as string in c# ?

Martin
  • 16,093
  • 1
  • 29
  • 48
  • To be fair, those are not compatible schemas. An array of strings is serialized differently than a single string within JSON, and the real intent can be represented in your code. However, by flip flopping between two schemas you've introduced accidental complexity. – Berin Loritsch Aug 03 '21 at 10:56
  • In short the second json your supplier is sending you is incorrect. It should be `"applicableBerthTypes":["LB"]`. Then everything would work. Question in situations like this is who do you talk to. I.e. are they responsible to change the misuse of your API, or do you have to complicate your API. – Berin Loritsch Aug 03 '21 at 11:00
  • @Berin Loritsch, But Supplier doesnot change their schemas...Is there anyway to handle this ? – VIGNESH WARAN Aug 03 '21 at 11:23

1 Answers1

0

Follow the structure below for the following data.

 LstrApidata = { "acuralBooking": null, "applicableBerthTypes":"LB" }
 BkgCfg data = JsonConvert.DeserializeObject<Dictionary<string, string>>(LstrApidata);

or

public class BkgCfg
{
    public string acuralBooking { get; set; }
    public string applicableBerthTypes { get; set; }
}

and

BkgCfg data = JsonConvert.DeserializeObject<BkgCfg>(LstrApidata);
Meysam Asadi
  • 6,438
  • 3
  • 7
  • 17