function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
PronowPronow 

Creating objects dynamically by getting fields values from JSON string

Hello there,

I get a JSON string from Javascript remoting function like this: '{"Name":"abc", "City":"xyz", "SobjectType":"Contact", "RecordTypeId":"Ab162EqwQDS5"}';

Now, I want to create sObject according to the field values received into the above string. How can I do this?

I refered Serialize and Deserialize methods of Apex JSON, however, they need ApexType as destination Class. They does not convert values directly into sObjects.

Shall I use JSON Parser methods? If yes then how?

Thanks in advance.
Best Answer chosen by Pronow
PronowPronow
Ideal code for the Process:

public static Boolean InsertSOjects(String sObjectApiName, String jSONSObject)
{
    Map<String, Object> fieldMap = (Map<String, Object>)JSON.deserializeUntyped(jSONSObject);
    Schema.SObjectType targetType = Schema.getGlobalDescribe().get(sObjectApiName);
    SObject newSobject = targetType.newSObject();
    Map<String, Schema.sObjectField> targetFields = targetType.getDescribe().fields.getMap();
    for (String key : fieldMap.keySet())
    {
        Object value = fieldMap.get(key);
        Schema.DisplayType valueType = targetFields.get(key).getDescribe().getType();
        if (value instanceof String && valueType != Schema.DisplayType.String)
        {
            String svalue = (String)value;
            if (valueType == Schema.DisplayType.Date)
                newSobject.put(key, Date.valueOf(svalue));
            else if(valueType == Schema.DisplayType.DateTime)
                newSobject.put(key, DateTime.valueOfGmt(svalue));
            else if (valueType == Schema.DisplayType.Percent || valueType == Schema.DisplayType.Currency)
                newSobject.put(key, svalue == '' ? null : Decimal.valueOf(svalue));
            else if (valueType == Schema.DisplayType.Double)
                newSobject.put(key, svalue == '' ? null : Double.valueOf(svalue));
            else if (valueType == Schema.DisplayType.Integer)
                newSobject.put(key, Integer.valueOf(svalue));
            else if (valueType == Schema.DisplayType.Base64)
                newSobject.put(key, Blob.valueOf(svalue));
            else
                newSobject.put(key, svalue);
        }
        else
            newSobject.put(key, value);
    }
    insert newSobject;
}

All Answers

PronowPronow
Thanks Harsha for your help with the link!
PronowPronow
Ideal code for the Process:

public static Boolean InsertSOjects(String sObjectApiName, String jSONSObject)
{
    Map<String, Object> fieldMap = (Map<String, Object>)JSON.deserializeUntyped(jSONSObject);
    Schema.SObjectType targetType = Schema.getGlobalDescribe().get(sObjectApiName);
    SObject newSobject = targetType.newSObject();
    Map<String, Schema.sObjectField> targetFields = targetType.getDescribe().fields.getMap();
    for (String key : fieldMap.keySet())
    {
        Object value = fieldMap.get(key);
        Schema.DisplayType valueType = targetFields.get(key).getDescribe().getType();
        if (value instanceof String && valueType != Schema.DisplayType.String)
        {
            String svalue = (String)value;
            if (valueType == Schema.DisplayType.Date)
                newSobject.put(key, Date.valueOf(svalue));
            else if(valueType == Schema.DisplayType.DateTime)
                newSobject.put(key, DateTime.valueOfGmt(svalue));
            else if (valueType == Schema.DisplayType.Percent || valueType == Schema.DisplayType.Currency)
                newSobject.put(key, svalue == '' ? null : Decimal.valueOf(svalue));
            else if (valueType == Schema.DisplayType.Double)
                newSobject.put(key, svalue == '' ? null : Double.valueOf(svalue));
            else if (valueType == Schema.DisplayType.Integer)
                newSobject.put(key, Integer.valueOf(svalue));
            else if (valueType == Schema.DisplayType.Base64)
                newSobject.put(key, Blob.valueOf(svalue));
            else
                newSobject.put(key, svalue);
        }
        else
            newSobject.put(key, value);
    }
    insert newSobject;
}
This was selected as the best answer
rajesh k 10rajesh k 10
Hi
I have one requirement,
Actually using below code i save object record in database dynamically.
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(strFieldName);
SObject myObj = targetType.newSObject();
insert myObj;

Note:using above code related object record only created.ButFields information is not saved.Here Fields add visualforce page Dynamically

but I gave some fields information here but those fields information is not saved in this record
How to save fields information also related object record Dynamically?

help me...............
PronowPronow
Hi Rajesh,

Line 1: gets object type.
Line 2: creates sObject of the fetched object type.
Line 3: inserts record of that object type.

You no where are referncing fields here.

Tell me the exact scenario that what exactly you want to do.
PronowPronow
Hi Rajesh,

I see the issue. On Save button, you are simply creating a blank record of some sObject. However, you are displaying all fields on your visualforce page. You need to bind those input fields on your visualforce page with the sObject that you are creating on Save button's action function.

Solution:
1. Create sObject record in Controller's constructor itself.
2. Bind that sObject recod's fields to input fields on your Visualforce page.
3. On Save button, just write code for insertion of that sObject record.
rajesh k 10rajesh k 10
Hi Pronow,
                 Using metadata api every time i will create fields.Those fields add to this visualforce page dynamically.With out adding fields to sobject every time tell me there is any solution.

Dynamically how to save thesfields in database?
Note:Here my object also Dynamically comming how i use controller's constructor
I try to this task from1 week

help me..............
PronowPronow
try this

public void doSave()
{
if( sObjectToBind != null )
  insert sObjectToBind;
}
rajesh k 10rajesh k 10
Hi sir ,
                It's fine but some time i got this error
System.DmlException: Insert failed. First exception on row 0 with id a0D9000000BbcSQEAZ; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
PronowPronow
Such error comes whenever you try to upsert a record with some field that refers parent object's field.

Like,

Contact.firstname =Right!
Contact.Accountid = Right!
Contact.Account.AccountName = Wrong!

Make sure you are not doing this.
rajesh k 10rajesh k 10
Hi,
         Super sir .Thank you very much.In an visualforce page my owner text field will be visible .How to give owner field as read only in an visualforce page every time object comming time Here ?


         
PronowPronow
Use apex:outputField instead of using apex:inputField for read-only items.
rajesh k 10rajesh k 10
Hi,
        How to add above page .

Your only my project finished sir......................
PronowPronow
<apex:outputField value="{!Contact.name}"/> - displaying Contact.Name

<apex:inputField value="{!Contact.name}"/> - displaying input field for Contact.Name
rajesh k 10rajesh k 10
Hi Pronow,
                 I want to Owner field automatically how to assign without using lookup Dynamically in an above page?
Note:I am a administrator
PronowPronow
1. Write a query to fetch Owner user:

List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'your.username@example.com' ];

2. Assign it to sObject owner:

if( lstUser != null && !lstUser.isEmpty() )
sObject.OwnerId = lstUser[0].Id;
rajesh k 10rajesh k 10
Hi,
          This is my object

string strFieldName = 'rajesh__'+strtemp + '__c';
PronowPronow
Give me your complete updated code so that I can suggest changes. 
rajesh k 10rajesh k 10
Hi Pronow,
                 In above code only i am asking.How to fix owner name .
PronowPronow
try this

public void doSave()
{
List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'your.username@example.com' ];
if( sObjectToBind != null && lstUser != null && !lstUser.isEmpty() )
sObjectToBind.put('OwnerId', lstUser[0].Id);
   insert sObjectToBind;
}
rajesh k 10rajesh k 10
Hi,
          Owner field Editable only not access my username at owner location.
       
PronowPronow
Hi Rajesh,

I didn't understand the error. Can you please paste it here as it is?
rajesh k 10rajesh k 10
Hi,
         When all field edit ,on that time Owner field Locaton I want my owner name.Don't use Lookup functionality how to fix my owner name owner field location everytime .
PronowPronow
Please send me screen shot of your form. I didn't understand your requirement. Also, please specify what is result and what do you expect.
rajesh k 10rajesh k 10
Hi,

         When enter Edit fields location means above code.I want My Owner name automatically how to add Owner location?
PronowPronow
Do you want your name to be displayed by default in Owner field as above?

rajesh k 10rajesh k 10
Hi,
            YES
PronowPronow
Put this code in DynamicBindingCls():

List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'your.username@example.com' ];
if( lstUser != null && !lstUser.isEmpty() )
 sObjectToBind.put('OwnerId', lstUser[0].Id);

And remove same from doSave()

rajesh k 10rajesh k 10
Hi,
         I added like this but my owner name is not came
DynamicBindingCls(){
List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'rajesh k' ];
if( lstUser != null && !lstUser.isEmpty() )
sObjectToBind.put('OwnerId', lstUser[0].Id);

}
PronowPronow
In salesforce, the Username field value for the object User should always be in email format e.g. 'your.username@example.com'. Check Username field value for the User record you are trying to refer.
rajesh k 10rajesh k 10
Hi,

I will use like this means Got error
DynamicBindingCls(){
List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'rajesh060708@gmail.com' ];
if( lstUser != null && !lstUser.isEmpty() )
sObjectToBind.put('OwnerId', lstUser[0].Id);

}
           I got following error

System.NullPointerException: Attempt to de-reference a null object

Class.rajesh.DynamicBindingCls.<init>: line 62, column 1

line 62:sObjectToBind.put('OwnerId', lstUser[0].Id);
PronowPronow
public DynamicBindingCls()
{

strtemp=ApexPages.currentPage().getParameters().get('DNF');
   string objectname ='rajesh__'+strtemp+'__c'; 
   
    listObjectFields =  new List<String>();
    Map<String , Schema.SObjectType> globalDescription = Schema.getGlobalDescribe();
    Schema.sObjectType sObjType = globalDescription.get(objectname);
  
    //take care of the sequence of following 5 statements

    sObjectToBind = sObjType.newSObject();
    Schema.DescribeSObjectResult r1 = sObjType.getDescribe();
   
    List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'rajesh060708@gmail.com' ];
if( sObjectToBind != null && lstUser != null && !lstUser.isEmpty() )
  sObjectToBind.put('OwnerId', lstUser[0].Id);

    Map<String , Schema.SObjectField> mapFieldList = r1.fields.getMap();
    Integer i = 0;
    for(Schema.SObjectField field : mapFieldList.values())
    {
        Schema.DescribeFieldResult fieldResult = field.getDescribe();
        if(fieldResult.isAccessible() && fieldResult.isUpdateable())
        {
            listObjectFields.add(fieldResult.getName());
        }
    }       
}
rajesh k 10rajesh k 10
Hi,
            Your super Sir.............................


Thank you very much............................
PronowPronow
Welcome!
rajesh k 10rajesh k 10

  Hi,
          I completed My MCA 2013 Batch.Now I have 8 months(Nov 2013 to present in chennai) of Experience.I completed Project on metadata api.There is any requirement please Inform me

My mail id:mahesh060708@gmail.com
PronowPronow
Sure. I'll let you know about opportunities if I find any.

Thanks!
rajesh k 10rajesh k 10
Thank U Sir............
rajesh k 10rajesh k 10
Hi Pronow,
                       Dynamically comming multipicklist fields how to find and display these fields as checkboxes Dynamically how?

please help me..........
rajesh k 10rajesh k 10
Hi Pronow,
                  How to display dynamically comming multiselectpicklistvalues as checkboxes in an visualforce page?