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

查看:28
本文介绍了从 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天全站免登陆