+ Start a Discussion

Issue in JSON parsing

I am looking to parse the below json response using Json deserializing

  "_total": 9,
  "values": [
      "_key": "1050817",
      "group": {"id": "1050817"}

The issue i am facing that I cannot declare a variable of name _total , it gives me an error saying no viable alternative at character '_' . Any idea how I can parse the above Json to get the value of total.
Vamsi KrishnaVamsi Krishna
one option is to replace/remove the _ in the JSON string before deserialising it..

something like
string strJSON = JSONString.replace('_','');

and then use strJSON to deserialize to your object.. so you don't need to declare variables with _ ... you can just call it "total" instead of "_total"
Cool GuyCool Guy
Use Like this.

String bodyString = '{  "_total": 9,  "values": [    {      "_key": "1050817",      "group": {"id": "1050817"}    }  ]}
String Total;
JSONParser parser = JSON.createParser(bodyString);
        While (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == '_total')) {
                if( parser.getText() != '' )
                    total = parser.getText();
Vamsi KrishnaVamsi Krishna
let us know if you got this working.. if our answers helped you to resolve pls mark a best answer..
if you got it working with your own solution please share it with the community for everyones benefit.. :-)
Hi Vamsi and Cool Guy , thank you for your responses! I followed  the approach of deserializing the JSON string into collections of primitive data types.

string jsonstr = '{"_total": 9,"values":[{"_key": "1050817","group": {"id": "1050817"}}]}';
Map<String, Object> mastermap = (Map<String, Object>) JSON.deserializeUntyped(jsonstr);