Sujeet Raman

Sujeet Raman

  • 862
  • 927
  • 354k

How to check a specific string contains in the Json object in core api

May 17 2021 2:01 PM
Hi
 
I have a function which will check given project name is include in the json object. For that I am not getting a proper json object in my response how to do that?
 
this is my object
 
{"projects":[{"name":"projects/sTest"},{"name":"projects/A345"},{"name":"projects/off"},{"name":"projects/dds"}]
 
i have one main method which will call public bool CheckDuplicate(string name) method to return whether any same name inside the object or not.
  1. public async Task<string> UploadData(string name, string url)  
  2. {  
  3. var hasMatch = CheckDuplicate(name);  
  4. //post project_name methode here which will happen only hasmatch is false.need to block same names  
  5. }  
  6. public bool CheckDuplicate(string name)  
  7. {  
  8. string pname = name.Substring(9, name.Length - 9);  
  9. HttpClient client = new HttpClient();  
  10. client.BaseAddress = new Uri(httpRequest);  
  11. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  12. HttpResponseMessage response = client.GetAsync(httpRequest).Result;  
  13. var result = response.Content.ReadAsStringAsync().Result;  
  14. in result i am getting my objects like  
  15. {"projects":[{"name":"projects/sTest"},{"name":"projects/A345"},{"name":"projects/off"},{"name":"projects/dds"}]  
  16. var JSONObj = JsonConvert.DeserializeObject(result);  
  17. // i am getting values in JSONObj but below code is not working  
  18. //cant check the given pname is there or not  
  19. var hasMatch = false;  
  20. for (var index = 0; index < JSONObj.length; ++index)  
  21. {  
  22. var Projects = JSONObj[index];  
  23. if (Projects.name == pname)  
  24. {  
  25. hasMatch = true;  
  26. }  
  27. else  
  28. {  
  29. hasMatch = false;  
  30. }  
  31. }  
  32. return hasMatch;  
  33. }

Answers (10)