2

This is the http response body - I want to get to "entries" 'id' and 'name' values, which are inside "item_collection". I'm having a hard time understanding how I proccess this.

{
      "type": "folder",
      "id": "0",
      "sequence_id": null,
      "etag": null,
      "name": "All Files",
      "created_at": null,
      "modified_at": null,
      "description": "",
      "size": 2020286,
      "path_collection": {
        "total_count": 0,
        "entries": []
      },
      "created_by": {
        "type": "user",
        "id": "",
        "name": "",
        "login": ""
      },
      "modified_by": {
        "type": "user",
        "id": "6513134877",
        "name": "Neurl_app_JWT",
        "login": "AutomationUser_702274_ytHCta28NB@boxdevedition.com"
      },
      "trashed_at": null,
      "purged_at": null,
      "content_created_at": null,
      "content_modified_at": null,
      "owned_by": {
        "type": "user",
        "id": "6513134877",
        "name": "Neurl_app_JWT",
        "login": "AutomationUser_702274_ytHCta28NB@boxdevedition.com"
      },
      "shared_link": null,
      "folder_upload_email": null,
      "parent": null,
      "item_status": "active",
      "item_collection": {
        "total_count": 3,
        "entries": [
          {
            "type": "folder",
            "id": "59148230210",
            "sequence_id": "0",
            "etag": "0",
            "name": "Child Folder with JWT"
          },
          {
            "type": "file",
            "id": "357400845689",
            "file_version": {
              "type": "file_version",
              "id": "377708076089",
              "sha1": "d11dcb484fa1e029e7e780683725992d8cea8649"
            },
            "sequence_id": "0",
            "etag": "0",
            "sha1": "d11dcb484fa1e029e7e780683725992d8cea8649",
            "name": "1.jpg"
          },
          {
            "type": "file",
            "id": "357392588484",
            "file_version": {
              "type": "file_version",
              "id": "377700062484",
              "sha1": "0dfa566cc317b86c801c7e8cac2832b80d0faa5c"
            },
            "sequence_id": "0",
            "etag": "0",
            "sha1": "0dfa566cc317b86c801c7e8cac2832b80d0faa5c",
            "name": "2.png"
          }
        ],
        "offset": 0,
        "limit": 100,
        "order": [
          {
            "by": "type",
            "direction": "ASC"
          },
          {
            "by": "name",
            "direction": "ASC"
          }
        ]
      }
    }

The class generated by JSON2Apex is the following:

//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//
// The supplied json has fields with names that are not valid in apex
// and so can only be parsed with explicitly generated code, this option
// was auto selected for you.

public class FolderInfoJson {

    public class Path_collection {
        public Integer total_count {get;set;} 
        public List<Entries> entries {get;set;} 

        public Path_collection(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'total_count') {
                            total_count = parser.getIntegerValue();
                        } else if (text == 'entries') {
                            entries = arrayOfEntries(parser);
                        } else {
                            System.debug(LoggingLevel.WARN, 'Path_collection consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Order {
        public String by_Z {get;set;} // in json: by
        public String direction {get;set;} 

        public Order(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'by') {
                            by_Z = parser.getText();
                        } else if (text == 'direction') {
                            direction = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Order consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Item_collection {
        public Integer total_count {get;set;} 
        public List<Entries_Z> entries {get;set;} 
        public Integer offset {get;set;} 
        public Integer limit_Z {get;set;} // in json: limit
        public List<Order> order {get;set;} 

        public Item_collection(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'total_count') {
                            total_count = parser.getIntegerValue();
                        } else if (text == 'entries') {
                            entries = arrayOfEntries_Z(parser);
                        } else if (text == 'offset') {
                            offset = parser.getIntegerValue();
                        } else if (text == 'limit') {
                            limit_Z = parser.getIntegerValue();
                        } else if (text == 'order') {
                            order = arrayOfOrder(parser);
                        } else {
                            System.debug(LoggingLevel.WARN, 'Item_collection consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public String type_Z {get;set;} // in json: type
    public String id {get;set;} 
    public Object sequence_id {get;set;} 
    public Object etag {get;set;} 
    public String name {get;set;} 
    public Object created_at {get;set;} 
    public Object modified_at {get;set;} 
    public String description {get;set;} 
    public Integer size {get;set;} 
    public Path_collection path_collection {get;set;} 
    public Created_by created_by {get;set;} 
    public Created_by modified_by {get;set;} 
    public Object trashed_at {get;set;} 
    public Object purged_at {get;set;} 
    public Object content_created_at {get;set;} 
    public Object content_modified_at {get;set;} 
    public Created_by owned_by {get;set;} 
    public Object shared_link {get;set;} 
    public Object folder_upload_email {get;set;} 
    public Object parent {get;set;} 
    public String item_status {get;set;} 
    public Item_collection item_collection {get;set;} 

    public FolderInfoJson(JSONParser parser) {
        while (parser.nextToken() != System.JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                    if (text == 'type') {
                        type_Z = parser.getText();
                    } else if (text == 'id') {
                        id = parser.getText();
                    } else if (text == 'sequence_id') {
                        sequence_id = parser.readValueAs(Object.class);
                    } else if (text == 'etag') {
                        etag = parser.readValueAs(Object.class);
                    } else if (text == 'name') {
                        name = parser.getText();
                    } else if (text == 'created_at') {
                        created_at = parser.readValueAs(Object.class);
                    } else if (text == 'modified_at') {
                        modified_at = parser.readValueAs(Object.class);
                    } else if (text == 'description') {
                        description = parser.getText();
                    } else if (text == 'size') {
                        size = parser.getIntegerValue();
                    } else if (text == 'path_collection') {
                        path_collection = new Path_collection(parser);
                    } else if (text == 'created_by') {
                        created_by = new Created_by(parser);
                    } else if (text == 'modified_by') {
                        modified_by = new Created_by(parser);
                    } else if (text == 'trashed_at') {
                        trashed_at = parser.readValueAs(Object.class);
                    } else if (text == 'purged_at') {
                        purged_at = parser.readValueAs(Object.class);
                    } else if (text == 'content_created_at') {
                        content_created_at = parser.readValueAs(Object.class);
                    } else if (text == 'content_modified_at') {
                        content_modified_at = parser.readValueAs(Object.class);
                    } else if (text == 'owned_by') {
                        owned_by = new Created_by(parser);
                    } else if (text == 'shared_link') {
                        shared_link = parser.readValueAs(Object.class);
                    } else if (text == 'folder_upload_email') {
                        folder_upload_email = parser.readValueAs(Object.class);
                    } else if (text == 'parent') {
                        parent = parser.readValueAs(Object.class);
                    } else if (text == 'item_status') {
                        item_status = parser.getText();
                    } else if (text == 'item_collection') {
                        item_collection = new Item_collection(parser);
                    } else {
                        System.debug(LoggingLevel.WARN, 'FolderInfoJson consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }

    public class File_version {
        public String type_Z {get;set;} // in json: type
        public String id {get;set;} 
        public String sha1 {get;set;} 

        public File_version(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'type') {
                            type_Z = parser.getText();
                        } else if (text == 'id') {
                            id = parser.getText();
                        } else if (text == 'sha1') {
                            sha1 = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'File_version consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Entries {

        public Entries(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        {
                            System.debug(LoggingLevel.WARN, 'Entries consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Created_by {
        public String type_Z {get;set;} // in json: type
        public String id {get;set;} 
        public String name {get;set;} 
        public String login {get;set;} 

        public Created_by(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'type') {
                            type_Z = parser.getText();
                        } else if (text == 'id') {
                            id = parser.getText();
                        } else if (text == 'name') {
                            name = parser.getText();
                        } else if (text == 'login') {
                            login = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Created_by consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Entries_Z {
        public String type_Z {get;set;} // in json: type
        public String id {get;set;} 
        public String sequence_id {get;set;} 
        public String etag {get;set;} 
        public String name {get;set;} 
        public File_version file_version {get;set;} 
        public String sha1 {get;set;} 

        public Entries_Z(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'type') {
                            type_Z = parser.getText();
                        } else if (text == 'id') {
                            id = parser.getText();
                        } else if (text == 'sequence_id') {
                            sequence_id = parser.getText();
                        } else if (text == 'etag') {
                            etag = parser.getText();
                        } else if (text == 'name') {
                            name = parser.getText();
                        } else if (text == 'file_version') {
                            file_version = new File_version(parser);
                        } else if (text == 'sha1') {
                            sha1 = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Entries_Z consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }


    public static FolderInfoJson parse(String json) {
        System.JSONParser parser = System.JSON.createParser(json);
        return new FolderInfoJson(parser);
    }

    public static void consumeObject(System.JSONParser parser) {
        Integer depth = 0;
        do {
            System.JSONToken curr = parser.getCurrentToken();
            if (curr == System.JSONToken.START_OBJECT || 
                curr == System.JSONToken.START_ARRAY) {
                depth++;
            } else if (curr == System.JSONToken.END_OBJECT ||
                curr == System.JSONToken.END_ARRAY) {
                depth--;
            }
        } while (depth > 0 && parser.nextToken() != null);
    }

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





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







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







}
  • Do you want to expose those fields in a visualforce page or add them to an SFDC Object? Where do you want these fields to be? What do you want to do with them? – Carlos Naranjo Nov 28 '18 at 10:20
  • Hi @CarlosNaranjo . I wanted to store these values in String variables. Thank you. – Rui Torres Nov 28 '18 at 10:31
  • Do you access this JSON from and endpoint URL? I assume that you are doing a HTTP Get method? – Carlos Naranjo Nov 28 '18 at 10:41
  • Yes, I do. I got a response.body() – Rui Torres Nov 28 '18 at 10:44
  • Ok, is that end point something you can expose here? – Carlos Naranjo Nov 28 '18 at 10:44
1

Sometimes its easier to use JSON.deserializeUntyped rather than creating wrapper class which contains variable names same as Apex keywords so you have to hack them out.

This can be done in just few lines of code if you know concrete JSON structure.

public class FromJSON{

 public static string input ='{"type":"folder","id":"0","sequence_id":null,"etag":null,"name":"All Files","created_at":null,"modified_at":null,"description":"","size":2020286,"path_collection":{"total_count":0,"entries":[]},"created_by":{"type":"user","id":"","name":"","login":""},"modified_by":{"type":"user","id":"6513134877","name":"Neurl_app_JWT","login":"AutomationUser_702274_ytHCta28NB@boxdevedition.com"},"trashed_at":null,"purged_at":null,"content_created_at":null,"content_modified_at":null,"owned_by":{"type":"user","id":"6513134877","name":"Neurl_app_JWT","login":"AutomationUser_702274_ytHCta28NB@boxdevedition.com"},"shared_link":null,"folder_upload_email":null,"parent":null,"item_status":"active","item_collection":{"total_count":3,"entries":[{"type":"folder","id":"59148230210","sequence_id":"0","etag":"0","name":"Child Folder with JWT"},{"type":"file","id":"357400845689","file_version":{"type":"file_version","id":"377708076089","sha1":"d11dcb484fa1e029e7e780683725992d8cea8649"},"sequence_id":"0","etag":"0","sha1":"d11dcb484fa1e029e7e780683725992d8cea8649","name":"1.jpg"},{"type":"file","id":"357392588484","file_version":{"type":"file_version","id":"377700062484","sha1":"0dfa566cc317b86c801c7e8cac2832b80d0faa5c"},"sequence_id":"0","etag":"0","sha1":"0dfa566cc317b86c801c7e8cac2832b80d0faa5c","name":"2.png"}],"offset":0,"limit":100,"order":[{"by":"type","direction":"ASC"},{"by":"name","direction":"ASC"}]}}';


    public static void parse(){
        Map<String,Object> jsonParsed =(Map<String,Object> ) JSON.deserializeUntyped(input);
        Map<String,Object> item_collection = ( Map<String,Object>) jsonParsed.get('item_collection');
        List<Object> entriesArray =( List<Object> ) item_collection.get('entries');

        for(Object inidividualEntries : entriesArray){
            Map<String,Object> ind = (Map<String,Object> )inidividualEntries;
            System.debug('Id = '+ ind.get('id'));
            System.debug('name = '+ ind.get('name'));
            System.debug('---------------------------------------------');
        }

    }

}

Which in turns prints the value you want

13:10:19.30 (75684710)|USER_DEBUG|[13]|DEBUG|Id = 59148230210
13:10:19.30 (75743456)|USER_DEBUG|[14]|DEBUG|name = Child Folder with JWT
13:10:19.30 (75766526)|USER_DEBUG|[15]|DEBUG|---------------------------------------------
13:10:19.30 (75810971)|USER_DEBUG|[13]|DEBUG|Id = 357400845689
13:10:19.30 (75834343)|USER_DEBUG|[14]|DEBUG|name = 1.jpg
13:10:19.30 (75843179)|USER_DEBUG|[15]|DEBUG|---------------------------------------------
13:10:19.30 (75873523)|USER_DEBUG|[13]|DEBUG|Id = 357392588484
13:10:19.30 (75901377)|USER_DEBUG|[14]|DEBUG|name = 2.png
13:10:19.30 (75910147)|USER_DEBUG|[15]|DEBUG|---------------------------------------------

Src : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_System_Json.htm#apex_System_Json_deserializeUntyped

  • This was just what I needed - thanks for your time, Pranay. – Rui Torres Nov 29 '18 at 15:22
1

I can show you how to insert these two fields to an object in SFDC. This example is just a basic approach on how you could build a JSON response structure in the future.

First you need to create and SFDC Object for this to work:

  1. Create Custom Object: Name: "Item Collection" - the API Name will be "Item_Collection__c".
  2. Create two fields: Name (data type Text) and IdJSON (data type number)
  3. Create an Apex class that will help us to deserialize our JSON response. Copy this class:

     public class Item_collection {
    
           public Decimal id {get; set;}
           public String name{get; set;}
      }
    

    Make sure the class name is the same than on this code (Item_collection).

To test this just open your developer console and fire this:

   // This is a small portion of your JSON response, normally you will use
   // a GET HTPP method to obtain the resonse from an ENDPOINT. 
   String responsebody ='[{"id": "59148230210", "name": "Child Folder with JWT" }]'; 


   // Here we use the JSON.desrialize() to transform the response using our 
   // class Item_collection
   List<Item_collection> listLoc = (List<Item_collection>)JSON.deserialize(responseBody, List<Item_collection>.class);

   List<Item_Collection__c> IteCollInsert = new List<Item_Collection__c>();

   for(integer i=0; i<listLoc.size(); i++)
   {
    Item_collection__c itenCollection = new Item_Collection__c();

    itenCollection= new Item_Collection__c(IdIdJSON__c = listLoc[i].id,
                                           name__c = listLoc[i].name
                                           ); 
    IteCollInsert.add(itenCollection);

    }
    insert IteCollInsert; 

This will create a new Item_Collection__c record with the values coming from:

String responsebody ='[{"id": "59148230210", "name": "Child Folder with JWT" }]';

You will get something similar to this in your org:

Item Collection after deserializing

When using the GET HTTP call you will use the endpoint and some extra lines of code to deserialize the all body. This, as I mentioned, is for you to see how to build the components that will allow you to access these fields. From here you can do further operations based on your requirements.

You could break things down and use all classes coming from your JSON response and manipulate their variables. In your case you are just looking for the list "entries" and those two values.

  • Most of the times the received JSON response structure is not in the hands of SF devs, thus they have to parse it no matter what – Pranay Jaiswal Nov 28 '18 at 13:57
  • This is just a Basic Example.... Pranay, don't stress your self to much :) – Carlos Naranjo Nov 28 '18 at 14:02
  • Just a thought, – Pranay Jaiswal Nov 28 '18 at 14:04
  • 1
    @PranayJaiswal if the JSON reponse structure have any modficiations all operations will suffer the impact of that modification/s no matter what JSON Methods are you using.. right? And I tried to explain how to bring data from a JSON response to an obejct becasue from 1 to 10 times we use a GET method in an HTTP calls, how many times we need to keep that data coming from the JSON response in an Object in SFDC? 8 of 10? , 9 of 10, .... 6 of 10?. As far as I understand in most cases you want to be able to do that for further calculations or data visualization. Just a thought, :) – Carlos Naranjo Nov 29 '18 at 10:53
  • Grateful for taking the time, Carlos. It was very clear. – Rui Torres Nov 29 '18 at 15:23

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.