How to deserialize a JSON list in Apex

Hi I have the a JSON string which is List of Account how do I deserialize the JSON using Apex

    [
  {
    "attributes": {
      "type": "Account",
      "url": "/services/data/v36.0/sobjects/Account/00158000002zBhUAAU"
    },
    "Id": "00158000002zBhUAAU",
    "Name": "Customer1"
  },
  {
    "attributes": {
      "type": "Account",
      "url": "/services/data/v36.0/sobjects/Account/00158000002zBhVAAU"
    },
    "Id": "00158000002zBhVAAU",
    "Name": "Customer2"
  },
  {
    "attributes": {
      "type": "Account",
      "url": "/services/data/v36.0/sobjects/Account/00158000002zBhWAAU"
    },
    "Id": "00158000002zBhWAAU",
    "Name": "PSA Client"
  },
  {
    "attributes": {
      "type": "Account",
      "url": "/services/data/v36.0/sobjects/Account/00158000002zBhXAAU"
    },
    "Id": "00158000002zBhXAAU",
    "Name": "Vendor1"
  },
  {
    "attributes": {
      "type": "Account",
      "url": "/services/data/v36.0/sobjects/Account/00158000007nCPlAAM"
    },
    "Id": "00158000007nCPlAAM",
    "Name": "Eraser"
  },
  {
    "attributes": {
      "type": "Account",
      "url": "/services/data/v36.0/sobjects/Account/00158000007nCPCAA2"
    },
    "Id": "00158000007nCPCAA2",
    "Name": "Eraser"
  },
  {
    "attributes": {
      "type": "Account",
      "url": "/services/data/v36.0/sobjects/Account/00158000007nEJpAAM"
    },
    "Id": "00158000007nEJpAAM",
    "Name": "ViolinBand"
  },
  {
    "attributes": {
      "type": "Account",
      "url": "/services/data/v36.0/sobjects/Account/00158000002m2VfAAI"
    },
    "Id": "00158000002m2VfAAI",
    "Name": "abc"
  },
  {
    "attributes": {
      "type": "Account",
      "url": "/services/data/v36.0/sobjects/Account/00158000007nEJkAAM"
    },
    "Id": "00158000007nEJkAAM",
    "Name": "GuitarBand"
  },
  {
    "attributes": {
      "type": "Account",
      "url": "/services/data/v36.0/sobjects/Account/00158000007nEJVAA2"
    },
    "Id": "00158000007nEJVAA2",
    "Name": "GuitarBand"
  },
  {
    "attributes": {
      "type": "Account",
      "url": "/services/data/v36.0/sobjects/Account/00158000007nENhAAM"
    },
    "Id": "00158000007nENhAAM",
    "Name": "ViolinBand"
  }
]

This is what I tried:

public class AccountList{
    public List<String> attributes {get;set;}
}


AccountList accDetails = (AccountList)JSON.deserialize(res.getBody(),AccountList.class);

Answer

Assuming that the JSON data is from a List<Account> in the first place (as it appears to be) you do not need to define your own class but instead can use the Account object type:

String s = res.getBody();
List<Account> accounts = (List<Account>) JSON.deserialize(s, List<Account>.class);

Attribution
Source : Link , Question Author : nevrekar_amey , Answer Author : Keith C

Leave a Comment