We are migrating a D7 site to D8 and I have an API endpoint that returns the current user that I need to migrate. In D7, I would do something like:
global $user;
$u = user_load($user->uid);
return drupal_json_output($u);
This ends up returning a body like:
{
"uid": "1111",
"name": "SomeUser",
"roles": [
"2": "authenticated",
"3": "premium"
],
"field_matched_nodes": [
"und": [
{
"target_id": "2222"
},
{
"target_id": "3333"
}
]
],
...
}
Now in D8, I'm trying to mimic the same thing. The key is that the return body needs to be exactly that is was in D7, or else the apps we have that use this endpoint won't work until push and update to the apps and our users update their app version.
So I'm trying something like:
$uid = \Drupal::currentUser()->id();
$current_user = User::load($uid);
$user_json = \Drupal::service('serializer')->serialize($user, 'json');
return JsonResponse($user_json, 200)
This gets me the user object in JSON, but it's structure is like:
{
"uid": [
{
"value": 1111
}
],
"name": [
{
"value": "SomeUser"
}
],
"field_matched_nodes": [
{
"target_id": 2222,
"target_type": "node",
"target_uuid": "3248789345-23894798324-328498234",
"url": "/en/node/2222",
},
{
"target_id": 3333,
"target_type": "node",
"target_uuid": "3248789345-23894798324-328498234",
"url": "/en/node/2222",
}
],
...
}
Some notable differences:
- Roles isn't even included in D8, but is in D7,
- Basic field values like name are nested as a value for key "value" in an object in an array in D8, where in D7 it was simply the value for the field key
- Custom fields aren't nested under "und" like they are in D7
Is there some sort of D7 serializer for D8 that constructs User objects as the same json structure it did for D8? Id be surprised if this doesn't exist, as I'm sure I'm not the only one who migrated to D8 with a public API...