You need to sign in to do that
Don't have an account?
Scott Spilker 12
Duplicate values in For Loop when iterating on List to create Map
Hi,
I am trying to iterate through a list of users using a For loop, but am receiving duplicate values when pushed to json.
The ID for Username 7 in my example is copied to all values, even though the username shows up correctly in the JSON.
Why is it pushing idForUser7 to all of them here?
{
"username 1" : {
"id" : "idForUser7"
},
"username 2" : {
"id" : "idForUser7"
},
"username 3" : {
"id" : "idForUser7"
},
"username 4" : {
"id" : "idForUser7"
},
"username 5" : {
"id" : "idForUser7"
},
"username 6" : {
"id" : "idForUser7"
},
"username 7" : {
"id" : "idForUser7"
}
}
As a side note, the reason I am going with this approach is to avoid the attributes/type/url when pushing an SObject Map to json.
"attributes" : {
"type" : "User",
"url" : "/services/data/v49.0/sobjects/User/0053t000007t21nAAA"
},
I am trying to iterate through a list of users using a For loop, but am receiving duplicate values when pushed to json.
The ID for Username 7 in my example is copied to all values, even though the username shows up correctly in the JSON.
Why is it pushing idForUser7 to all of them here?
{
"username 1" : {
"id" : "idForUser7"
},
"username 2" : {
"id" : "idForUser7"
},
"username 3" : {
"id" : "idForUser7"
},
"username 4" : {
"id" : "idForUser7"
},
"username 5" : {
"id" : "idForUser7"
},
"username 6" : {
"id" : "idForUser7"
},
"username 7" : {
"id" : "idForUser7"
}
}
As a side note, the reason I am going with this approach is to avoid the attributes/type/url when pushing an SObject Map to json.
"attributes" : {
"type" : "User",
"url" : "/services/data/v49.0/sobjects/User/0053t000007t21nAAA"
},
public static string getActiveUsers() { Map<string, Map<String, String>> userActiveMap = new Map<string, Map<String, String>>(); Map<String, String> userActiveMapValue = new Map<String, String>(); try{ for(List<User> activeUsersList : [ select id,username,LastLoginDate,ProfileId from User where IsActive = True]) { for (User u : activeUsersList) { userActiveMapValue.clear(); userActiveMapValue.put('id', string.valueof(u.id)); userActiveMap.put( string.valueof(u.Username) , userActiveMapValue); } } } catch(DmlException e) { System.debug('An unexpected error has occurred: ' + e.getMessage()); } return json.serialize(userActiveMap); }
Try the below code:
Thanks,
Maharajan.C
All Answers
Try the below code:
Thanks,
Maharajan.C
To fix this issue, you may need to change line 12 to:
userActiveMapValue = new Map<String, String>();