0

I'm trying to convert a JSON file, which has information from one or more objects. I saw that one way was to transform the JSON String to JSONParser and loop to generate the objects.

I want to convert these objects to SObject to do the proper treatment instead of converting straight to the specific object, such as Account. The problem is that an error occurs at conversion time:

"Exception: System.JSONException: Nested object for polymorphic foreign key must have a field attributes before any other fields.".

Please, anyone have an idea how I could do this conversion?

        String jsonText = '[{"Id":"0015800001PTKzHAAX","Name":"test1"},{"Id":"0015800001PTKxpAAH","Name":"test2"}]';
        JSONParser parser = JSON.createParser(jsonText);
        system.debug('JSONParser: ' + parser);

        while (parser.nextToken() != null)
        {
            if (parser.getCurrentToken() == JSONToken.START_ARRAY)
            {
                while (parser.nextToken() != null)
                {
                    if (parser.getCurrentToken() == JSONToken.START_OBJECT)
                    {
                        SObject obj = (SObject)parser.readValueAs(SObject.class);
                        system.debug('Object: ' + obj);
                    }
                }
            }
        }
1

your Json string is not suitable string for Sobject type, it should be below format. your Json string doesn't have type and attribute properties

  String jsonText =   '{"records": [{
      "attributes":  {
        "type" : "Contact",
        "url" : "/services/data/v47.0/sobjects/Contact/003r000000HIYhMAAX"
    }, 
    "Id":"003r000000HIYhMAAX","Name":"test1"
    },{
      "attributes":  {
        "type" : "Contact",
       "url" : "/services/data/v47.0/sobjects/Contact/003r000000HIXXXAA5"
    }, "Id":"003r000000HIXXXAA5","Name":"test2"}
    ]}';

for above string you can use below syntax to convert for Sobject class

  Map<String, Object> cObjMap = (Map<String, Object>) JSON.deserializeUntyped(jsonText);
String cObjJson = JSON.serialize(cObjMap);

SObject customObject = (SObject)JSON.deserialize(cObjJson, Sobject.class);
    System.debug('sobject data: '+customObject);
1

The message itself is quite descriptive. If you serialize any SObject, you will see what they mean. The payload will look like:

{
    {
        "type":"Account",
        "url":"/services/data/v47.0/sObjects/001..."
    },
    "Id": "001..."
}

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.