Click here to Skip to main content
15,877,376 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have one API which gives different responses in reply:
For example:
  1. API gives response:
    JSON
    {
        "status_id": 200,
        "status_msg": "Successful",
        "unique_trans_id": "CLIENTAPI202305260134469",
        "info": {
            "case_id": "MG.0523.30"
        }
    }

  2. Sometimes, it gives the following response:
    JSON
    {
        "status_id": 400,
        "status_msg": "Bad Request",
        "unique_trans_id": "CLIENTAPI202306050146459",
        "info": [
            "cp_state : value must be a valid string",
            "cp_city : value must be a valid string"
        ]
    }

  3. Sometimes, it give response:
    JSON
    {
        "status_id": 409,
        "status_msg": "Duplicate Request",
        "unique_trans_id": "CLIENTAPI202310270276322",
        "info": [
            "Duplicate request for reference ID I/2023/400018/00097601"
        ]
    }

Following is my output class:
C#
public class OutputInfo
   {
       public string status_id { get; set; }
       public string status_msg { get; set; }
       public string unique_trans_id { get; set; }
       public infodetails info { get; set; }
   }

   public class infodetails
   {
       public string case_id { get; set; }
   }

Following is the code where I convert json into class:
C#
if (httpresponsemessage.IsSuccessStatusCode)
               {
                   var responseData =
               httpresponsemessage.Content.ReadAsStringAsync().Result;
                   strinputjson = responseData.ToString();
                   ErrorHandler.LogSteps(strinputjson, "JsonOutput");

                   tResponse =JsonConvert.DeserializeObject<TResponse>
                   (strinputjson);
               }


I want to convert json response into my OutputInfo class.

Now, the current code is giving me an error in second and third response. Kindly help me with this.

What I have tried:

I tried a lot of different code, but did not get success.
Posted
Updated 27-Oct-23 7:36am
v2

1 solution

This sort of API response is a nightmare to work with, but seems to be quite popular amongst the loosely-typed language crowd.

To read it in C#, you will need a custom JSON converter. For example:
C#
public class OutputInfo
{
	public string status_id { get; set; }
	public string status_msg { get; set; }
	public string unique_trans_id { get; set; }
	public InfoDetailsOrErrorList info { get; set; }
}

[JsonConverter(typeof(InfoDetailsOrErrorListConverter))]
public class InfoDetailsOrErrorList
{
	public string case_id { get; set; }
	public string[] errors { get; set; }

	public sealed class InfoDetailsOrErrorListConverter : JsonConverter<InfoDetailsOrErrorList>
	{
        public override CanWrite => false;
        
		public override InfoDetailsOrErrorList ReadJson(
            JsonReader reader, 
            Type objectType, 
            InfoDetailsOrErrorList existingValue, 
            bool hasExistingValue, 
            JsonSerializer serializer)
		{
			switch (reader.TokenType)
			{
				case JsonToken.Null:
				{
					return null;
				}
				case JsonToken.StartArray:
				{
					string[] errors = serializer.Deserialize<string[]>(reader);
					return new InfoDetailsOrErrorList { errors = errors };
				}
				case JsonToken.StartObject:
				{
					var temp = new InfoDetailsOrErrorList();
					serializer.Populate(reader, temp);
					return temp;
				}
				default:
				{
					throw new JsonException();
				}
			}
		}
		
		public override void WriteJson(
            JsonWriter writer, 
            InfoDetailsOrErrorList value, 
            JsonSerializer serializer)
		{
			throw new NotImplementedException();
		}
	}
}

Unfortunately, your consuming code will now need to check whether the info property contains an errors array (cases 2 and 3) or a case_id (case 1).
 
Share this answer
 
Comments
Maciej Los 27-Oct-23 11:25am    
5ed!
Graeme_Grant 27-Oct-23 19:36pm    
5ed! I should add this to the growing list of examples on my articles: Working with Newtonsoft.Json in C# & VB[^] & Working with System.Text.Json in C#[^]
Akshay malvankar 28-Oct-23 10:34am    
How to identify info is object or info is an array from api response
Graeme_Grant 29-Oct-23 5:14am    
Look at the code given ... starting here:
switch (reader.TokenType)
Akshay malvankar 29-Oct-23 5:16am    
TokenType it's given object in both response ,info property is object or info property is an array

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900