diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index a7875a868..dfd205d40 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -57,8 +57,9 @@ class JSONEncoder(json.JSONEncoder): 'You should be using a schema renderer instead for this view.' ) elif hasattr(obj, '__getitem__'): + cls = (list if isinstance(obj, (list, tuple)) else dict) try: - return dict(obj) + return cls(obj) except Exception: pass elif hasattr(obj, '__iter__'): diff --git a/tests/test_encoders.py b/tests/test_encoders.py index c66954b80..c104dd5a5 100644 --- a/tests/test_encoders.py +++ b/tests/test_encoders.py @@ -8,6 +8,7 @@ from django.utils.timezone import utc from rest_framework.compat import coreapi from rest_framework.utils.encoders import JSONEncoder +from rest_framework.utils.serializer_helpers import ReturnList class MockList: @@ -93,3 +94,10 @@ class JSONEncoderTests(TestCase): """ foo = MockList() assert self.encoder.default(foo) == [1, 2, 3] + + def test_encode_empty_returnlist(self): + """ + Tests encoding an empty ReturnList + """ + foo = ReturnList(serializer=None) + assert self.encoder.default(foo) == []