[SalesForce] JSON String to custom object list

Here is breakdown of what I am trying to achieve

  1. Read List of questions from a file uploaded by user
  2. Convert it into JSON format
  3. Create a List of custom object
  4. Insert this list into database

I have been able to perform first two steps using jQuery and below is the JSON string I am able to get

    [{"Question__c":"this is is first question","proposal__c":"a0GJ000000GZphSMAT","Name":"Question 1"},
{"Question__c":"this is second question","proposal__c":"a0GJ000000GZphSMAT","Name":"Question 2"},
{"Question__c":"this is third question","proposal__c":"a0GJ000000GZphSMAT","Name":"Question 3"},
{"Question__c":"this is fourth quest","proposal__c":"a0GJ000000GZphSMAT","Name":"Question 4"},
{"Question__c":"This is fifth question","proposal__c":"a0GJ000000GZphSMAT","Name":"Question 5"}] 

Now I want to call Apex method using Salesforce Remoting and convert this JSON format to a Question Object List and perform insert.

Sample code for what I am trying to do

         ProposalDetail.insertQuestion(
             qJSONString,
             function(results, event) {
                 //all questions inserted successfully;
             }
          );

Sample APEX Code

@RemoteAction
global static String insertQuestion(String questionData){
    String status = 'false';
    //List<Question__c> quesObject = (Question__c) System.JSON.deserialize(questionData, Question__c.class);
}//end of insert record

I have read about deserialize method but I am not sure how to go about it?

Edit:
For the sake of completion here is how my final controller looked like:

@RemoteAction
global static String insertQuestion(String questionData){
    String status = 'false';
    Question__c[] records = (Question__c[])JSON.deserialize(questionData, List<Question__c>.class);
    try{
        insert records;
        status = 'true';
    }
    catch(Exception e){
     status = 'false;
    }
    return status;
}//end of insert record

Best Answer

You're trying to insert an array, not a single record, from your JSON, but in your Apex Code, you're trying to deserialize just a single question. Instead, you can do this:

Question__c[] records = (Question__c[])JSON.deserialize(questionData, List<Question__c>.class);

Also, using remote action methods, you can SObjects in directly:

@RemoteAction public static String insertQuestions(Question__c[] questionData) {

This skips the bit about having to deserialize it manually, but you can't catch those errors in Apex Code either, if you use this technique. It also might require some small change to your JavaScript to include an "attributes" parameter (deserialize a standard SObject to see what I'm talking about).

Related Topic