none
Dictionary RRS feed

  • Question

  • Hi,

    I am trying to retrieve a json array in vb.net using visual studio 2010 and i am getting the "given key not found in dictionary" error.  Your help will be highly appreciated

    My JSON array: [{"status":1,"desc":"Successfully retrieved 5 categories..","data":[{"2":{"name":"ACCOUNTS","price":null,"image":null},"5":{"name":"DRIVER FBR","price":null,"image":null},"4":{"name":"GENERAL","price":null,"image":null},"10":{"name":"MASTER DATA","price":null,"image":null},"3":{"name":"QUERIES","price":null,"image":null}}]}]

    My code:   

    Imports System.IO
    Imports System.Net
    Imports System.Web.Script.Serialization

    Public Class Form1

        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

       Dim uriString As String = "http://1stbn.co.za/dev/api/_lkpCompanyQMCategories.php?cid=1&limi=50"
            Dim uri As New Uri(uriString)

            'Make HTTP Request
            Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
            request.Method = "GET"


            'Get HTTP Response
            Dim response As HttpWebResponse = request.GetResponse()

            'Read HTTP Response
            Dim read As New StreamReader(response.GetResponseStream())
            Dim raw As String = read.ReadToEnd()

      Dim dic As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(raw)


            For Each item As Object In dic
                TextBox1.Text = item("data").ToString + "-" + item("data").ToString + vbNewLine
                Console.WriteLine(item.ToString)

                'TextBox1.Text = item("data").ToString & vbCrLf
                'TextBox1.Text = item("status").ToString & vbCrLf
                'TextBox1.Text = item("desc").ToString & vbCrLf
            Next

    End Sub

    End Class

    Monday, July 8, 2019 10:38 AM

Answers

  • The following works for me in a console program.

    Dim list1 As List(Of Object) = New JavaScriptSerializer().Deserialize(Of List(Of Object))(raw)
    Dim dic1 As Dictionary(Of String, Object) = list1(0)
    Console.WriteLine(dic1("status").ToString())
    Console.WriteLine(dic1("desc").ToString())
    Console.WriteLine(dic1("data").ToString())

    Note that a JSON array is not a dictionary in .Net. You can use a List for a JSON array. For this data there is only one item in the array, so that makes it confusing.



    Sam Hobbs
    SimpleSamples.Info


    Tuesday, July 9, 2019 7:24 PM
  • I suggest using a console program to work on doing this as I have. It is easier to use console programs for working out how to do it then you can copy the code to your main program when you have it working. For my program raw is a string variable with the JSON as a constant string.

    The following will show the contents of dic1("data"). Note that I assume there will always be one item in that array. Also, I assume that the numbers (such as 2, 5, 4, 10, 3 in this example) will vary, so I don't know how you will need to handle that. 

    For Each kvp1 As KeyValuePair(Of String, Object) In dic1("data")(0)
        System.Console.WriteLine(kvp1.Key)
        For Each kvp2 As KeyValuePair(Of String, Object) In kvp1.Value
            If kvp2.Value IsNot Nothing Then
                System.Console.WriteLine("---- " + kvp2.Key + "=" + kvp2.Value)
            End If
        Next
    Next



    Sam Hobbs
    SimpleSamples.Info


    Wednesday, July 10, 2019 4:32 PM

All replies

  • Hello,

    Try to do opposite - form the dictionary you need and serialize it in JSON.

    There could be a difference in serialized text. 

    Second - you deserialize as List of Objects - there are no dictionary - there are just Objects. 


    Sincerely, Highly skilled coding monkey.

    Monday, July 8, 2019 11:10 AM
  •  private HttpWebRequest CreateDEAPIRequest(string apiURL)
            {
                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
                request.PreAuthenticate = true;       
                return request;

            }

      HttpWebRequest request = CreateAPIRequest(apiURL);
                var pgResponse = (HttpWebResponse)request.GetResponse();
                StreamReader streamReader = new StreamReader(pgResponse.GetResponseStream(), true);

                string target = string.Empty;
                target = streamReader.ReadToEnd();
                List<Message> msg = JsonConvert.DeserializeObject<List<Message>>(target);
                streamReader.Close();


    if the Api is returning a list, it should be captured in the List<Message> msg object declared.

    To create a dictionary you can iterate and add the name value paid to a dictionary object.

    Hope this helps you to retrieve the correct set of data. you can transform C# to VB.net online if required.

    Monday, July 8, 2019 12:11 PM
  • The following works for me in a console program.

    Dim list1 As List(Of Object) = New JavaScriptSerializer().Deserialize(Of List(Of Object))(raw)
    Dim dic1 As Dictionary(Of String, Object) = list1(0)
    Console.WriteLine(dic1("status").ToString())
    Console.WriteLine(dic1("desc").ToString())
    Console.WriteLine(dic1("data").ToString())

    Note that a JSON array is not a dictionary in .Net. You can use a List for a JSON array. For this data there is only one item in the array, so that makes it confusing.



    Sam Hobbs
    SimpleSamples.Info


    Tuesday, July 9, 2019 7:24 PM
  • Hi,

    Thank you for the response.

    I have tried your code and i am getting the following when i run the program:

    1
    Successfully retrieved 5 categories..
    System.Object[]

    How can i retrieve the items within data, i want to retrieve the following. Is it possible perhaps?

    {"2":{"name":"ACCOUNTS","price":null,"image":null}, "5":{"name":"DRIVER FBR","price":null,"image":null},"4":{"name":"GENERAL","price":null,"image":null},

    Wednesday, July 10, 2019 6:52 AM
  • I suggest using a console program to work on doing this as I have. It is easier to use console programs for working out how to do it then you can copy the code to your main program when you have it working. For my program raw is a string variable with the JSON as a constant string.

    The following will show the contents of dic1("data"). Note that I assume there will always be one item in that array. Also, I assume that the numbers (such as 2, 5, 4, 10, 3 in this example) will vary, so I don't know how you will need to handle that. 

    For Each kvp1 As KeyValuePair(Of String, Object) In dic1("data")(0)
        System.Console.WriteLine(kvp1.Key)
        For Each kvp2 As KeyValuePair(Of String, Object) In kvp1.Value
            If kvp2.Value IsNot Nothing Then
                System.Console.WriteLine("---- " + kvp2.Key + "=" + kvp2.Value)
            End If
        Next
    Next



    Sam Hobbs
    SimpleSamples.Info


    Wednesday, July 10, 2019 4:32 PM
  • Thank you very much, It works!!!!!
    Thursday, July 11, 2019 8:01 AM
  • Hi,

    I am glad you have got your solution,please mark the helpful as answer. It will be beneficial to other community.

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, July 11, 2019 8:20 AM
    Moderator