Json Additional attribute how to handle without code change RRS feed

  • Question

  • User-588203678 posted


    I have Json like 




    "Age": 23


    This application is linked to other application to receive data. Later this Json has some additional fields like Interest,Hobbies etc and it adds on , how to handle in code .




    "Age": 23,


    "Hobbies": stamps


    We are everytime touching the code by writing if condition for interest,hobbies etc. 

    I do not want to write like this using if . Any alternative solution to handle in Get,post,merge,put.

    using (var client = new HttpClient())
      client.BaseAddress = new Uri("baseurl");

      var data = JObject.
      var response = client.PostAsync("/urlpath",
                                      new StringContent(JsonConvert.SerializeObject(data),
                                      Encoding.UTF8, "application/json")).Result;


      var responseContent = await response.Content.ReadAsStringAsync();

      dynamic json = JsonConvert.DeserializeObject(responseContent);
      dynamic r = json.result;

      result = r.someproperty.ToString().Equals("resultdata");

    Wednesday, March 24, 2021 1:36 AM

All replies

  • User1686398519 posted

    Hi guhananth1, 

    When the json data you want to return is different (for example, the two test data you provided), you can still read the data without modifying the code.

    If this is the case, you can refer to the example I provided.


            public string Post()
                string jsonstring = "";
                Random random = new Random();
                var test = random.Next(1, 5);
                if (test >3)
                    jsonstring = "{\"id\":20,\"Name\":\"Sam\",\"Age\":23}";
                    jsonstring = "{\"id\":20,\"Name\":\"Sam\",\"Age\":23,\"Interest\":\"Music\",\"Hobbies\":\"stamps\"}";
                return jsonstring;


              var data = new Employee {  ID=1 };
              var client = new HttpClient();
                var response = client.PostAsync("https://localhost:44365/api/values", new StringContent(JsonConvert.SerializeObject(data),Encoding.UTF8, "application/json")).Result;
                var responseContent = await response.Content.ReadAsStringAsync();
                dynamic json = JsonConvert.DeserializeObject(responseContent);
                dynamic testdic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
                foreach (var kv in testdic)
                    var key=kv.Key.ToString();
                    var value= kv.Value.ToString();
                    var result = value.Equals("resultdata");

    Here is the result. 

    Best Regards,


    Wednesday, March 24, 2021 9:51 AM