How to Analyze Json Data to Normal Data in C #

advertisements

I am beginner in c#, I have output from the website like {"result":"Invalid"} with my c# program, It seems to be Json ,I want to display these data as normal string and display it in message box and use those parsed data for validation

Program:

private async void Button_Click(object sender, RoutedEventArgs e)
{
  var username = Username.Text;
  var password = passbox .Password;
  var postMessage = new StringContent(string.Format("username={0}&password={1}", username, password), Encoding.UTF8 , "application/x-www-form-urlencoded");
  var response = await (new HttpClient()).PostAsync("http://xxx.xx.net/xx.php", postMessage);
  var responseBody = await response.Content.ReadAsStringAsync();
  MessageBox.Show( responseBody );
}

I want to know how to display the responseBody as normal string ?


Ideal solution depends on how complex Json string you got. If it has only single property-value pair like posted in question :

{"result":"Invalid"}

I think simple string manipulation logic will bring you the value ("Invalid") easily. Like this naive code :

var jsonString = "{\"result\":\"Invalid\"}";
//remove "{" and "}" from sting
var result = jsonString.Replace("{", "").Replace("}", "");
//separate property name from it's value
var pair = result.Split(':');
//property will contain property name : "result"
var property = pair[0];
//value will contain property value : "Invalid"
var value = pair[1];

Otherwise, if JSON response is more complex, it is not reliable to use string manipulation. I'd suggest to go with Newtonsoft.Json library as also suggested by @Mohammad.