1

I am trying to process the data from a NativeObject, but I have found a small issue with the naming of the object properties. The JavaScript code for the object is:

var mainObject = {
    "innerObject" : {
        "234" : {
            "property1" : "1",
            "property2" : "2"
        }
    }
}

The method I use to process it in Java looks like this:

public void processNative(NativeObject obj) {

    if(NativeObject.hasProperty(obj, "innerObject")) {
        NativeObject no = (NativeObject)NativeObject.getProperty(obj, "innerObject");
        Object[] propIds = NativeObject.getPropertyIds(no);
        for (int i = 0; i < propIds.length; i++) {
            String key = propIds[i].toString(); 
            NativeObject numObj = (NativeObject)NativeObject.getProperty(no, key); 
            //do more processing here
        }
    }
}

This code will throw this exception: java.lang.ClassCastException: org.mozilla.javascript.UniqueTag cannot be cast to org.mozilla.javascript.NativeObject.

If I cast to a UniqueTag I can actually get the proper value, which in this case will be UniqueTag.NOT_FOUND.

I find this a bit confusing since I am getting the property key from the object itself and it actually exists in the JavaScript code.

If I change the name of the object from "234" to "car" the code works as expected, so I am assuming that there is an issue with the naming. From this post I understand that property names can be any type of string, so there should be no problems with having a string made of digits.

So I guess a follow-up question would be: Is there a way for me to solve this issue without having to do the renaming?

One more thing I need to mention is that I only have access to the JavaScript code and to the Java method. Everything else is a black box.

Thanks!

Community
  • 1
  • 1
gookman
  • 2,527
  • 2
  • 20
  • 28

1 Answers1

0

I had this problem in Scala too. NativeObject supports 2 get methods get(int, Scritable) and get(string, Scriptable). So if a property key is a number string I convert it to an int and use get(int, yourObject)

http://www.jarvana.com/jarvana/view/org/mozilla/rhino/1.7R3/rhino-1.7R3-javadoc.jar!/org/mozilla/javascript/ScriptableObject.html#get%28int,%20org.mozilla.javascript.Scriptable%29

hotienvu
  • 675
  • 5
  • 9
  • This might be the solution to the problem. The way I solved it is by adding a **$** in front of the key, thus turning it into a string. I'll have to check if your solution works as well. – gookman Jun 15 '13 at 11:17