[SalesForce] System.JSONException: Malformed JSON: Expected ‘[‘ at the beginning of List/Set when deserializing JSON object in apex

I'm trying to pass an array of strings from JavaScript to apex. I am initially converting the array into a JSON object and then stringifying the object and passing it into my apex code as a string. So far this works but I am encountering an error when trying to convert my JSON string into a list of string. Below is my code samples:

<apex:page controller="testController" id = "pageId">
    <apex:form id="form">
        <button type="button" onclick="passToApex()">Pass Array to Apex class</button>
        <apex:inputHidden value="{!stringIN}" id="hiddenfield"/>
        <apex:actionFunction name="stringINName" action="{!passedInMethod}" rerender="Form"/>
    </apex:form>
    <apex:pageBlock>
        <apex:pageblockTable value="{!StringValues}" var="SList" rendered="{!StringValues != null}"></apex:pageblockTable>
    </apex:pageBlock>
    <script type="text/javascript">
        function passToApex(){
            var J = {"0": "String 'One' ","1": "String 'Two' ","2": "String 'Three' "};
            var JStr = JSON.stringify(J);
            document.getElementById('{!$Component.pageId.form.hiddenfield}').value = JStr;
            stringINName();
     }
    </script>
</apex:page>

Apex:

public with sharing class testController {
    public String stringIN{get; set;}
    public list<string> strList = new list<string>();
    public set<string> StrSet = new set<string>();
    public pageReference passedInMethod(){
        return null;
    }
    public set<string> getStringValues(){
        try{
            list<string> strList = (List<String>)JSON.deserialize(stringIN,  List<String>.class);
            StrSet.addAll(strList);
        }catch (System.NullPointerException e){

        }
        if(StrSet.size() > 0){
            return StrSet;
        }
        return null;
    }       
}

Essentially I would like to convert the JSON in a string set in the form : {"String 'One'", "string 'Two'", "string 'Three'"}

What am I not doing right that may be causing this error? Thanks.

Best Answer

JSON arrays are simply written as '[ "Item1", "Item2", "Item3" ]'.

As for generating the correct array, you should be using JavaScript built-ins, instead of trying to write your own JSON by hand:

var inputs = [];
inputs.push("String 'One'")
inputs.push("String 'Two'")
inputs.push("String 'Three'")
document.getElementById('{!$Component.pageId.form.hiddenfield}').value = JSON.stringify(inputs);
Related Topic