Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Read JSON in C#

Read JSON in C#

Scheduled Pinned Locked Moved C#
csharpcomjsonquestionannouncement
5 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    Jassim Rahma
    wrote on last edited by
    #1

    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[^]

    Technology News @ www.JassimRahma.com

    Richard DeemingR R B 3 Replies Last reply
    0
    • J Jassim Rahma

      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[^]

      Technology News @ www.JassimRahma.com

      Richard DeemingR Offline
      Richard DeemingR Offline
      Richard Deeming
      wrote on last edited by
      #2

      Use Json.NET[^] - you can add a reference via NuGet[^]:

      Install-Package Newtonsoft.Json

      You can then either use LINQ to JSON[^] to read the property:

      JObject result = JObject.Parse(strsb);
      bool isValid = (bool)result["valid"];

      or create strongly typed classes to represent the result:

      public class ResponseData
      {
      public bool valid { get; set; }
      public IList<string> messages { get; set; }
      public string iban { get; set; }
      public BankData bankData { get; set; }
      public IDictionary<string, bool> checkResults { get; set; }
      }

      public class BankData
      {
      public string bankCode { get; set; }
      public string name { get; set; }
      }

      ...

      var result = JsonConvert.DeserializeObject<ResponseData>(strsb);
      bool isValid = result.valid;


      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

      1 Reply Last reply
      0
      • J Jassim Rahma

        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[^]

        Technology News @ www.JassimRahma.com

        R Offline
        R Offline
        Ravi Bhavnani
        wrote on last edited by
        #3

        To add to Richard's answer, you can use this free handy-dandy online tool to generate C# classes from JSON.  You may want to rename the generated class names to be more developer friendly. json2csharp - generate c# classes from json[^] :cool: /ravi

        My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

        Richard DeemingR 1 Reply Last reply
        0
        • R Ravi Bhavnani

          To add to Richard's answer, you can use this free handy-dandy online tool to generate C# classes from JSON.  You may want to rename the generated class names to be more developer friendly. json2csharp - generate c# classes from json[^] :cool: /ravi

          My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #4

          Visual Studio already has a "Paste JSON as classes" option, since 2012.2: ‘Paste JSON As Classes’ in ASP.NET and Web Tools 2012.2 RC | .NET Web Development and Tools Blog[^] The output isn't perfect, but it's usually a good place to start. :)


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          1 Reply Last reply
          0
          • J Jassim Rahma

            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[^]

            Technology News @ www.JassimRahma.com

            B Offline
            B Offline
            Bernhard Hiller
            wrote on last edited by
            #5

            When I look at the message text above, I think you can get confused by their convention. Their "valid": true seems to mean that the message you sent them was syntactically correct. But you are likely interested in the IBAN. And that's given in a different part of the message: "checkResults": { "bankCode": false }. Well, I tried that service with my IBAN, and got following result (I edited the number on the response below):

            {
            "valid": true,
            "messages": [],
            "iban": "DE...........",
            "bankData": {
            "bankCode": "",
            "name": ""
            },
            "checkResults": {}
            }

            WTF... A valid IBAN is indicated by an empty checkresult and an empty messages array.

            1 Reply Last reply
            0
            Reply
            • Reply as topic
            Log in to reply
            • Oldest to Newest
            • Newest to Oldest
            • Most Votes


            • Login

            • Don't have an account? Register

            • Login or register to search.
            • First post
              Last post
            0
            • Categories
            • Recent
            • Tags
            • Popular
            • World
            • Users
            • Groups