I am getting below Jsonstring. Now I need to get value for Salesforce_ABT__c in a string Salesforce. Can someone please help me?

JSON String:

   loginUserJson@{"attributes":{"type":"User","url":"/services/data/v40.0/sobjects/User/005F0000002ex2jIAA"},"Id":"005F0000002ex2jIAA","Name":"iRep Admin3","IsActive":true,"Email":"anilkumar.lingaraju@abbvie.com","SmallPhotoUrl":"https://abv-irep-us--NGT--c.cs71.content.force.com/profilephoto/005/T","Primary_Territory_vod__c":"JBB00","User_Franchise_abv__c":"GI Care","Salesforce_ABT__c":"HOMEOFFICE","ProfileId":"00eA0000000wwNpIAI","Profile":{"attributes":{"type":"Profile","url":"/services/data/v40.0/sobjects/Profile/00eA0000000wwNpIAI"},"Name":"System Administrator","Id":"00eA0000000wwNpIAI"}}

I am trying to do below approach but it gives error.


 loginuser = [Select Id,Name,IsActive,email,SmallPhotoUrl, Primary_Territory_vod__c, User_Franchise_abv__c,Salesforce_ABT__c, Profile.Name from User where Id = :UserInfo.GetUserId()];    
        loginUserJson = JSON.serialize(loginuser);
       JSONObject json = (JSONObject) JSONSerializer.toJSON(loginUserJson);
        String Franchise= json.getString('User_Franchise_abv__c');
        String Salesforce= jsonObject.getString('Salesforce_ABT__c');
        String Territory= jsonObject.getString('Primary_Territory_vod__c');

But is gives error JSONObject is invalid type. Please help me doing this.


Always worth pasting JSON into e.g. https://jsonformatter.curiousconcept.com/ to more easily see it's structure.

The Apex JSON class is usually the best thing to use. You can do this if its a small bit of code:

Map<String, Object> p = (Map<String, Object>) JSON.deserializeUntyped(loginUserJson);
String Franchise = (String) p.get('User_Franchise_abv__c');

Or if you are doing a lot of manipulation of the JSON you can generate classes to represent the data using json2apex and work with those.

(I presume the code you post is a contrived example; in it you could access the data using loginuser directly without going via JSON.)

  • 1
    I like jsbeautifier which works great for JSON too. But yeah good advice. – Adrian Larson Jun 30 '17 at 9:14

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.