从JSON创建动态对象时面临的问题 [英] Facing issue in creating dynamic objects from JSON

查看:110
本文介绍了从JSON创建动态对象时面临的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在满足一个要求,即用户可以仅通过提供生产URL和凭据就可以从生产框中获取数据并将其插入开发人员沙箱中.我能够获取数据,但不知为何无法将JSON转换为所需的对象类型.由于我是Salesforce的新手,所以请不要介意基本问题.

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);
        }

通过以上逻辑,我试图按对象获取数据并将其插入开发沙箱中,我能够完美地以JSON进行获取,但无法从JSON转换为所需的对象.问题是我无法对对象或类型名称进行硬编码,因为它将是对象列表.如果您需要其他任何详细信息,请提前告诉我.也可以使用任何其他方法,但是只能通过顶点编码.

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.

推荐答案

您是否已经尝试过 JSON2Apex ,如果不是,那将是一个很好的候选人.

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

这篇关于从JSON创建动态对象时面临的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆