0

I am trying to send a post request to ContentVersion to migrate my contentVersions from point A to B :

i build the body like this :

body = ('{"Title" :"'+Title+'",
          "PathOnClient":"' +PathOnClient+'",
          "ContentLocation" :"' +ContentLocation +'",
          "FirstPublishLocation": { "External_ID__c" : 
                "'+FirstPublishLocationId+'"},
          "versionData" :"'+VersionDataString+ '"}');
reqInsert.setBody( body);

I know that the problem comes from this polymorphic field :

"FirstPublishLocation": { "External_ID__c" : "'+FirstPublishLocationId+'"},

but I don't know how to fix it ?

I have

Error 400 Bad request

has any one did a similar thing before ?

Thank you !

1 Answer 1

0

Don't try to write your own JSON. You've made a mess of things. And I don't mean you specifically, I mean nobody should be writing straight JSON to strings. I don't do it, and I've been writing Apex since it was a Developer Preview.

For the record, your problem is that you can't include physical newlines in strings. If I were ever to try this, I'd try to make it look more like real JSON:

String body = 
      '{' +
        '"Title":"' + Title + '",' +
        '"PathOnClient":"' + PathOnClient + '",' +
        '"ContentLocation":"' + ContentLocation + '",' +
        '"FirstPublishLocation": {' +
          '"External_ID__c":' + '"' + FirstPublishLocationId + '"' +
        '},' +
        '"versionData":"' + VersionDataString + '"' +
      '}';

But you shouldn't do this. What happens if your External ID ends up containing a " character, or PathOnClient for that matter? There's a reason why we're given tools for generating correct JSON.

You can easily write valid JSON with JSON.serialize, like this:

body = JSON.serialize(
  new Map<String, Object> {
    'Title' => title,
    'PathOnClient' => pathOnClient,
    'ContentLocation' => ContentLocation,
    'FirstPublishLocation' => new Map<String, String> {
      'External_ID__c' => firstPublishLocationId
    },
    'versionData' => versionDataString
  }
);

Not only is this far easier to read, it's less error-prone, and has some compile-time safety.

3
  • Thank you for your response, i am trying your solution but when i system.debug(body) , it only contains versionData value i can't see why ? Commented Sep 16, 2022 at 15:38
  • i admit that the way i build my json is not the clean way but can i do this : '"FirstPublishLocation": {' + '"External_ID__c":' + '"' + FirstPublishLocationId + '"' to set the value of my External_ID__c is it possible to do it with the polymorphic field FirstPublishLocation Commented Sep 16, 2022 at 15:46
  • @AmirBouzid Kind of. You actually need to include the type of the record as well. Read my answer on the correct syntax.
    – sfdcfox
    Commented Sep 16, 2022 at 15:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .