Sidebar

JSON.stringify() throws an exception

0 votes
10.8K views
asked Feb 17, 2016 by mike-r-7535 (13,830 points)

I am building a JavaScript Object from messageCache, but when I use JSON.stringify(), it throws this exception:

EvaluatorException: Java class "[Ljava.lang.reflect.Constructor;" has no public instance field or method named "toJSON"

 

2 Answers

+1 vote
 
Best answer

JSON.stringify() is a JavaScript function, and it only accepts JavaScript types.  This error occurs when a Java object (likely a Java String from a messageCache.getValue()) is added as an attribute in your JavaScript object.

The short answer is to convert the values to a JavaScript type object like this:

var newMessage = {};
newMessage.firstName = "" + messageCache.getValue("firstName");
newMessage.middleName = "" + messageCache.getValue("middleName");
newMessage.lastName = "" + messageCache.getValue("lastName");
qie.info(JSON.stringify(newMessage));
 
By prepending the value with an empty string, it converts it to be a JavaScript string, and this will work.
 
After some additional research, JSON.stringify has a "replacer" parameter which we can be use to convert Java objects into JavaScript equivilants.  This can be done like this:
var replacer = function(key, value) {
   var returnValue = value;
   try {
      if (value.getClass() !== null) { // If Java Object
         // qie.debug(key + ': value.getClass() = ' + value.getClass());
         if (value instanceof java.lang.Number) {
            returnValue = 1 * value;
         } else if (value instanceof java.lang.Boolean) {
            returnValue = value.booleanValue();
         } else { // if (value instanceof java.lang.String) {
            returnValue = '' + value;
         }
      }
   } catch (err) {
      // No worries... not a Java object
   }
   return returnValue;
};
 
qie.info(JSON.stringify(newMessage, replacer));
I have uploaded a sample channel configuration with a more complete example:
 
 
 
 
answered Feb 18, 2016 by mike-r-7535 (13,830 points)
selected Feb 18, 2016 by mike-r-7535
+1 vote
Another non-replacer way is to use the Javascript new String() constructor:

var newMessage = {};
newMessage.firstName = new String( messageCache.getValue("firstName"));
newMessage.middleName = new String( messageCache.getValue("middleName"));
newMessage.lastName = new String( messageCache.getValue("lastName"));
qie.info(JSON.stringify(newMessage));

Doing the same thing: forcing conversion of a Java string to a Javascript string

 

(Personally, I'd prefer

    var newMessage = {
        firstName: new String( messageCache.getValue("firstName")),
        middleName: new String( messageCache.getValue("middleName")),
        lastName: new String( messageCache.getValue("lastName")),
    }
    qie.info(JSON.stringify(newMessage));

but that's me.)
answered Apr 27, 2017 by (160 points)
...