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
David9133David9133 

How to assign JSOn string values to the fields in the test class in salesforce

Passing the values from the visualforce page as JSON string and Assigning the values, Need the help in test class how to pass the JSON string to the test class as i am getting Null Pointer exception while saving the Method.

<apex:page controller="skillproficiencycontroller" id="p"> <apex:form id="f"> <script> var state = {}; function passState() { document.getElementById("p:f:hiddenField").value = JSON.stringify(state); passStateToController(); } function myFunction( value, id) { state[id] = value; console.log(state); } </script> <apex:inputHidden value="{!hidden}" id="hiddenField"/> <apex:pageBlock > <apex:pageblockTable value="{!skilllist}" var="s"> <apex:column value="{!s.Name}"/> <apex:column headerValue="Proficiency"> <apex:selectRadio value="{!Selected}" onclick="myFunction(this.value,'{!s.id}');"> <apex:selectOptions value="{!items}" /> </apex:selectRadio> </apex:column> </apex:pageblockTable> <apex:pageBlockButtons location="bottom"> <apex:commandButton onclick="passState(); return false;" value="Save" /> <apex:actionFunction name="passStateToController" action="{!Save}" reRender="hiddenField" /> </apex:pageBlockButtons> </apex:pageBlock> </apex:form> </apex:page>


public void Save() { List<Skill_Details__c >skilldetailslist = new List<Skill_Details__c >(); JSONParser parser = JSON.createParser(hidden); while (parser.nextToken() != null) { if (parser.getCurrentToken() != JSONToken.START_OBJECT && parser.getCurrentToken() != JSONToken.END_OBJECT){ Skill_Details__c sd = new Skill_Details__c(); sd.Skill__c = id.valueOf(parser.getText()); parser.nextToken(); sd.Proficiency__c = parser.getText(); skilldetailslist.add(sd); } } //system.debug(skilldetailslist); Insert skilldetailslist; }

 
NagendraNagendra (Salesforce Developers) 
Hi David,

First and foremost sincerely regret delayed reply.
MyController mc = new MyController();

mc.hidden = "some json";
Not sure of the exact sequence of things in your controller, test class, etc or the exact line that is throwing the error because those details are missing from your question BUT:

You have ONE token and Value defined in your code:

vfac.hidden = '[ {\"a0H8A000001XO5QUAW\":\"First\"} ]';

Then in your class you grab the first token:

while (parser.nextToken() != null) {

and the text

When you get to this line you get the next token but it does not exist so the getText fails because the parser is null (no next token).
parser.nextToken();
            sd.Proficiency__c = parser.getText();
Kindly mark this post as solved if the information help's so that it gets removed from the unanswered queue and becomes a proper solution which results in helping others who are really in need of it.

Best Regards,
Nagendra.P