0

I am having trouble deserializing the JSON request received.

Below is the JSON format I receive,

    {
        header:{
        worker count: 2},
        Worker:{
            name:emp1
        },
        Worker:{
            name:emp2
        },
        Worker:{
            name:emp3
        }
    }

With the below code, I tried to put them in the array -

string jsonstring = request.requestbody.tostring();
string regex = ',\\"([^\\"]+)\\"\\:+\\{'; // regex for ,"worker" :{
String resultStr = JSONreqstring.replaceFirst(regex, ',"Workers": [{'); //replace first occurance of "worker" with start of the workers array
String resultStr1 = resultStr.replace('"Worker":{', '{'); // remove subsequent worker and put them in the array
String resultStr2 = resultStr1.removeEnd('}'); 
resultStr3 = resultStr2 + ']}'; 

The resultstr3 would be -

{
    header:{
    worker count: 2},
    Workers:[{
        name:emp1
    },
    {
        name:emp2
    },
    {
        name:emp3
    }]
}

Then I am able to deserialize this, the problem is, if the json request has more number of records, i get the regex too complicated error as salesforce has 1M character limit on the string for comparision.

  • please show what have you tried so far. – devforce Dec 2 '19 at 9:03
4

This is not a valid JSON, you might want to format it like this

   {
    "header": {
        "worker count": "2"
    },
    "Worker": [{
            "name": "emp1"
        },
        {
            "name": "emp2"
        },
        {
            "name": "emp3"
        }
    ]
}

array of worker Objects you put as value of "Worker" attribute.

1

My personal preference is to use the JSONParser.readValueAs

This will avoid the headache of parsing a JSON node by node.

1/ First thing you need to do is to create an Apex POJO class with the same structure of the JSON. Different tools you can use: JSON2Apex / jsonschema2pojo (This will generate a JAVA class but the code is very similar to Apex)

2/ Secondly, once you have the Apex Class created, for example HeaderWorkerJSON you can just in few lines of code, parse that JSON Text and create an object instance in memory (see code below)

String jsonString ='{YOUR_JSON}'
JSONParser parser = JSON.createParser(jsonString);
HeaderWorkerJSON myParsedJSONObject = (HeaderWorkerJSON) parser.readValueAs(HeaderWorkerJSON.class);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.