1

I have a JSON string which the value of 'clueContent' is a serialized JSON String.

When I try to deserialize this JSON string to the resp2Obj inner class, it raise an error with message:

'System.JSONException: Unexpected character ('t' (code 116)): was expecting comma to separate OBJECT entries at [line:1, column:32]'

Could anyone help to figure out where I did wrong.

    String resp3 = '{"id1":"10","clueContent":"[{\"test\":\"13245678912\"}]"}';
    System.debug('resp3:'+resp3);
    resp2Obj test11 = (resp2Obj)JSON.deserialize(resp3, resp2Obj.class);
    System.debug(test11);

    Class resp2Obj{
       String clueContent;
       String id1;
    }

You could generate the 'resp3 JSON String' with below codes, but cannot deserialize it back. Is it a bug?

    resp2Obj test12 = new resp2Obj();
    test12.id1='10';
    test12.clueContent = '[{"test":"13245678912"}]';
    System.debug('test12 json:'+JSON.serialize(test12));
1

Your string is not correctly escaped. You can observe this by running

String resp3 = '{"id1":"10","clueContent":"[{\"test\":\"13245678912\"}]"}';
System.debug(resp3);

You'll see

11:55:20:003 USER_DEBUG [2]|DEBUG|{"id1":"10","clueContent":"[{"test":"13245678912"}]"}

Note the absent backslashes. This is not valid JSON.

In Apex string literals, you must escape backslashes:

String resp3 = '{"id1":"10","clueContent":"[{\\"test\\":\\"13245678912\\"}]"}';

This is one reason why it is generally a bad idea to build JSON by concatenating strings - it's very easy to make this type of error. Instead, always build data structures and serialize the real objects.

| improve this answer | |
  • Thanks for your answer, after pre-proccess this JSON string with below regex, I'm able to deserialize the string. String regex2 = '(?<=(\"clueContent\":\\s?\")).*?]'; Matcher matcher=Pattern.compile(regex).matcher(resps); – Zas Jan 17 at 3:38
  • 1
    I would strongly suggest you not manipulate JSON via regex in this way. Instead, make sure that you always work with valid JSON. In this case, your JSON is invalid because you are representing it incorrectly in a string literal. – David Reed Jan 17 at 4:58

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.