Facing issue in creating dynamic objects from JSON

徘徊边缘 提交于 2020-01-06 06:46:34

问题


I am working on the requirement where a User can fetch the data from production box and insert it into developer sandbox by just giving production URL and creds. I am able to fetch data but somehow not able to convert the JSON to required object type. As I am newbie in Salesforce please don't mind for basic questions.

Below is the working logic and issue:

for(DataMigrationNAP__c d : dataMigrationNAP) // this loop will give all NAP object names and its corresponding fields like {'Account','Name,Phone,Id'},{'Opportunity', 'ID,Name, blah,blah'}...
{         
    final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
            String soql = 'Select '+d.NAPObjectFields__c+' From '+d.Name+' a limit ' + recordCount;
            theUrl.getParameters().put('q',soql);
            request = new HttpRequest();
            request.setEndpoint(theUrl.getUrl());
            request.setMethod('GET');
            request.setHeader('Authorization', 'OAuth ' + SESSION_ID);
            String body = (new Http()).send(request).getBody();
            JSONParser parser = JSON.createParser(body);

            do{
                parser.nextToken();
            }while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));
            parser.nextToken();

            String typeName = 'List<' + d.Name + '>';
            Type t  = Type.forName(typeName);
            List<sobject> acc1 = (List<sobject>) parser.readValueAs(t);
            insert acc1;
            System.debug('Values inserted : ' + acc1);
        }

Through above logic I am trying to fetch the data Object by Object and insert it into dev sandbox, I am able to fetch perfectly in JSON but not able to convert from JSON to required object. The issue is I can't hardcode Object or Type name because it will be a list of objects. Please let me know if you need any other detail and thanks in advance. Open for any other approach as well but it should be through apex coding only.


回答1:


Have you tried JSON2Apex already, if not than this could be good candidate.



来源:https://stackoverflow.com/questions/45811763/facing-issue-in-creating-dynamic-objects-from-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!