none
Read JSON in C# RRS feed

  • Question

  • Hi,

    I have a web service which returns JSON string like this:

    {
      "valid": true,
      "messages": [
        "Cannot validate bank code length. No information available.",
        "Cannot get BIC. No information available."
      ],
      "iban": "BH00000000000000000000",
      "bankData": {
        "bankCode": "",
        "name": ""
      },
      "checkResults": {
        "bankCode": false
      }
    }

    I am able to get it using below code:

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://openiban.com/validate/" + txtIBAN.Text.Trim());
    try
    {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
    
            string strsb = reader.ReadToEnd();
                        
        }
    }
    catch (WebException ex)
    {
        WebResponse errorResponse = ex.Response;
        using (Stream responseStream = errorResponse.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText
        }
        throw;
    }
    

    but I want to know can I now read the value valid if it's rue or false?

    Thanks,

    Jassim

    Thursday, July 28, 2016 5:04 PM

Answers

  • Hello Jassim,

    If you want to just convert the message body to json then Newtonsoft is a great, easy to use project for serializing json.  

    To install:

    Install-Package Newtonsoft.Json

    Docs: http://www.newtonsoft.com/json/help/html/serializingjson.htm

    You could use the JsonReader if you wanted to keep things simple: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonReader.htm


    Jeff

    Thursday, July 28, 2016 10:40 PM

All replies

  • Hi,

    just get some JSON parser via nuget and use it for the parsing or you write your own parser.

    The easiest possibility would be to use a Regex to parse the "valid" item, which could be problematic if the item is not always at the same position in the JSON string.

    Just select one possibility and let us know which one if you need futher help.

    Regards,

    David


    Thursday, July 28, 2016 7:14 PM
  • Hello Jassim,

    If you want to just convert the message body to json then Newtonsoft is a great, easy to use project for serializing json.  

    To install:

    Install-Package Newtonsoft.Json

    Docs: http://www.newtonsoft.com/json/help/html/serializingjson.htm

    You could use the JsonReader if you wanted to keep things simple: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonReader.htm


    Jeff

    Thursday, July 28, 2016 10:40 PM