1

Is there a way I can pass JSON string in the JSON body.

Example, Here is my JSON Body,

{"description":"Some Text","machinename":"add JSON","ipaddress":"192.128.0.0","version":"v3"}

In "machinename", I want to add this other JSON string so that it gets stored in the text field as JSON string ({ "id": "0684D0000004VgeTTE", "success": true, "errors": []}, something like below,

{"description":"Some Text","machinename":"{  "id": "0684D0000004VgeTTE", "success": true,    "errors": []}","ipaddress":"192.128.0.0","version":"v3"}

Every time I try to use snippet above, I believe its breaking because of quotation marks ("). Can I skip quotation mark to pass Json sting in JSON?

  • 2
    why can't you send it as not json string, but json object, and then before saving it to text field serialize to json string? – Oleksandr Berehovskyi Jun 21 '17 at 8:19
5

I suggest:

String encoded = JSON.serialize('{"id": "0684D0000004VgeTTE", "success": true, "errors": []}');

that generates this string that is a valid JSON value:

"{\"id\": \"0684D0000004VgeTTE\", \"success\": true, \"errors\": []}"

that can be set as the "machinename" value. It keeps the logic in the JSON world.

  • Of course. That's a better solution. – Caspar Harmer Jun 21 '17 at 8:41
2

There may be a better way to do this, but URLEncoding it seems to work.

Try this:

String jsonStr = '{"id":"0684D0000004VgeTTE","success":true,"errors":[]}';
String encoded = EncodingUtil.urlEncode(jsonStr, 'UTF-8');
String jsonStr2 = '{"description":"Some Text","machinename":"' + encoded + '","ipaddress":"192.128.0.0","version":"v3"}';

Map<String,Object> obj = (Map<String,    Object>)JSON.deserializeUntyped(jsonStr2);
System.debug(EncodingUtil.urlDecode((String)obj.get('machinename'), 'UTF-8'));

Of course it all depends what you are going to do with it on the other end, but this may be useful for you.

0

Using single quotes instead of double quotes for the sub JSON worked for me.

    {  
       "description":"Some Text",
       "machinename":"
         {  
            'id':'0684D0000004VgeTTE',
            'success':true,
            'errors':[  

            ]
          }
       ",
      "ipaddress":"192.128.0.0",
      "version":"v3"
   }

PostMan

  • Try adding same json here, it looks like some extra chacters are added to the initial string, which would be hard to remove by JSON parsers. – Pranay Jaiswal Jul 19 at 10:42

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.