0

AN external system for some reason sends a node in a JSON as a String instead of an array like below:

"vr_sch": "[{"type":"Record","tableName":"hpd","SId":"868","frequency":"ONCE"}]"

The Apex class which would be used to deserialize look like below( A small logic which would actually parse this node)

  } else if (text == 'vr_sch') {
         vrsch = arrayOfvrSchema(parser);
  }

private static List<vrsch> arrayOfvrSchema(System.JSONParser parseObj) {
    List<vrsch> res = new List<vrsch>();
    if (parseObj.getCurrentToken() == null){
        parseObj.nextToken();
    }
    while (parseObj.nextToken() != System.JSONToken.END_ARRAY) {
        res.add(new vrsch(parseObj));
    }
    return res;
}

The above code can only work if "vr_sch": "[{"type":"Record","tableName":"hpd","SId":"868","frequency":"ONCE"}]" is not a string but an array. How can I work around parsing this node as a an array. Any idea?

  • 2
    Typically it's much easier and clearer to work with serialization rather than a parser. – Adrian Larson Jan 4 '19 at 19:17
  • Agree. The json had a complex structure and I used JSON2APex to generate the class thought it would be much easier to do that way. Is there any way I can solve this using parser? Thanks! – SfdcBat Jan 4 '19 at 19:33
  • You can still deserialize it as an array if you know that this is going to be the structure. And then individually get the contents using say list.get(0) -- returns type and so on. – Jayant Das Jan 4 '19 at 19:46
  • Why not use JSON.deSerializedUnTyped , it returns Map and you can do String parsing on its content by removing leading and trailing comma ". – Pranay Jaiswal Jan 4 '19 at 19:56