I am trying to read the JSON request in my REST service in Apex class. I am getting the JSON_PARSER_ERROR as below.
"message": "Unexpected parameter encountered during deserialization:
accid at [line:3, column:14]"
I believe I am doing something wrong (obviously 🙂 ) while reading the JSON string in the class.
Can anyone guide me where I'm going wrong. Checked the herokuapp. Its parsing the string using JSON parser and tokens. http://json2apex.herokuapp.com/
So cant I use deserialze to read this JSON string?
My Class:
global class AMSAcctsWrper{
public AMSAcctsWrper()
{
AMSAccts = new List<AMSAccts>();
}
public List<AMSAccts> AMSAccts;
}
public class AMSAccts {
Public String accid;
....
}
doPut method:
@HttpPut
global static Resp doPut(String req) {
try{
AMSAcctsWrper accParse = (AMSAcctsWrper) System.JSON.deserialize(req, AMSAcctsWrper.class);
String accid = accParse.AMSAccts[0].accid;
system.debug ('accid ' + accParse.AMSAccts[0].accid);
……
My JSON Request:
{
"req":
[ {
"accid":"1256",
....
},
{
"accid":"1276",
....
}
]
}
Best Answer
Because you are manually deserializing you do not need to put the "req" wrapper in your JSON. This is only required when Salesforce is doing the deserializing for you with the method signature so that it knows what top level variables to assign the values to.
Note that you do not necessarily need to deserialize into a wrapper class either: you can deserialize straight into your list of
AMSAccts
objects. Here is a small sample of what the JSON would look like in the two approaches:Using Wrapper
JSON
APEX
Straight To List
JSON
APEX
As you can see, when your JSON is an array you can just start it with an opening brace. The second approach assumes that you move
AMSAccts
to a top level class. If you left it in the wrapper you would need to reference it asAMSAcctsWrper.AMSAccts
.Hope this helps!