0

JSON deserializeUntyped is causing trouble and I could not understand why it would convert a Array of data to something that is neither an array nor a similar string?

To reproduce I am executing this in Execute Anonymous Dev Console:

String s = '{ "data" : [ "powerCord", "test" ] }';
system.debug('Data String :: '+s);
Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(s);
system.debug('Deserialized To MAP :: '+m);
system.debug('Reading Map (data) :: '+m.get('data'));
List<String> l = (List<String>)JSON.deserialize(String.valueOf(m.get('data')), List<String>.class);
system.debug('@@ '+l);

Error I get:

FATAL_ERROR System.JSONException: Unexpected character ('(' (code 40)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]

Is there something wrong in my code here?

3

No, there's nothing wrong with your code. The parentheses are simply how System.debug() prints a List value. Note that System.debug() is not a JSON serialization; it's an idiosyncratic logging representation that may not align with any other representation of the underlying data. Your data is being deserialized correctly.

If you want a more standardized log output, you can serialize your data structure back to JSON and System.debug() that output.

3
  • I've updated my question with proper example code. The error received when I deserialize the m.get'data') node to it's actual data type.
    – VarunC
    Jul 13 '21 at 15:57
  • 3
    @VarunC You've changed your question in a way that makes my answer not make sense, but it's fundamentally the same problem: String.valueOf() does not perform a JSON serialization; it yields the same representation used by System.debug(). If you want JSON, you have to explicitly use JSON.
    – David Reed
    Jul 13 '21 at 15:59
  • Sorry. I should have Edited without removing the original question. I realize that now. I also just tried JSON.serialize() instead of String.valueOf() and it worked. Thanks for pointing that out.
    – VarunC
    Jul 13 '21 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.