Quantcast
Channel: Xojo Programming Forum - Latest topics
Viewing all articles
Browse latest Browse all 3827

KeyNotFoundException when dynamically using class property names

$
0
0

I am trying to write a function that will fill a class with JSON data using that class’s property names as the key. I am getting keyNotFoundException for many of the values. But not if I type them manually. It’s only the values that I generate dynamically from an instance of the class that cause keyNotFoundException.

Oddly, it’s not even all keys. For example, the key “DocTypeKey” works just fine. But the key “cnt_open” fails. As you can see in the code below, manually typing “cnt_open” as the key name works, but when it is derived from the class property it doesn’t.

I have tried trimming, replacing characters, copying into a new string character by character. It’s so strange.

Any ideas? Thanks!

TLDR:

This works:

prop.Value(c) = jsonDict.Value("cnt_open")

This doesn’t:

dim sName as string
sName = prop.Name //sName = cnt_open
prop.Value(c) = jsonDict.Value(sName) //. <--- FAILS WITH KEYNOTFOUNDEXCEPTIONxx

Even though both values are “cnt_open”.

Full Code:

For Each jsonDict As Xojo.Core.Dictionary In jsonArray
  
  dim c as new clsDocType
  Dim classInfo As Introspection.TypeInfo = Introspection.GetType(c)
  
  // Loop through each property in the class
  For Each prop As Introspection.PropertyInfo In classInfo.GetProperties()
    if prop.PropertyType.Name <> "DateTime" then //skip this, we generate datetimes from strings later
      
      try
        if prop.Name = "cnt_open" then //THIS IS MY TEST CASE
          prop.Value(c) = jsonDict.Value("cnt_open") //WHEN I TYPE IT MANUALLY, it works
          dim sName as string
          sName = prop.Name  //HERE sName = cnt_open but I am trying to make sure there are no hidden characters
          sName = sName.Trim
          sName = sName.ReplaceLineEndings("")
          
          //Here I'm going even further by moving each character into a new string one by one
          dim i as integer
          dim sNew as string
          for i = 0 to sName.Length - 1
            sNew = sNew + sName.Middle(i, 1)
          next
          
          //AFTER ALL THAT, the value of sNew is still "cnt_open"
          prop.Value(c) = jsonDict.Value(sNew) //. <--- FAILS WITH KEYNOTFOUNDEXCEPTION
        end if
        
        
        // Set the property value dynamically
        prop.Value(c) = jsonDict.Value(prop.Name)
      catch err as KeyNotFoundException
        dim sKey as string = prop.Name
        
        Dim keyList As string
        
        For Each entry As Xojo.Core.DictionaryEntry In jsonDict
          keyList = keyList + entry.Key + ", "
        Next
        
        break //Key Not found?!
        
      end Try
    end if
  Next
  
  aDocTypeSummaries.Add(c)
Next

7 posts - 2 participants

Read full topic


Viewing all articles
Browse latest Browse all 3827

Trending Articles