diff --git a/slumber/serialize.py b/slumber/serialize.py index 0e73f3d..c933f42 100644 --- a/slumber/serialize.py +++ b/slumber/serialize.py @@ -15,6 +15,14 @@ except ImportError: _SERIALIZERS["yaml"] = False +ordered_dict_defined = True +try: + from collections import OrderedDict +except ImportError: + try: + from ordereddict import OrderedDict + except ImportError: + ordered_dict_defined = False class BaseSerializer(object): @@ -45,7 +53,10 @@ class JsonSerializer(BaseSerializer): key = "json" def loads(self, data): - return json.loads(data) + if ordered_dict_defined: + return json.loads(data, object_pairs_hook=OrderedDict) + else: + return json.loads(data) def dumps(self, data): return json.dumps(data) diff --git a/tests/serializer.py b/tests/serializer.py index 68b2332..2c01123 100644 --- a/tests/serializer.py +++ b/tests/serializer.py @@ -2,14 +2,29 @@ import slumber import slumber.serialize +ordered_dict_defined = True +try: + from collections import OrderedDict +except ImportError: + try: + from ordereddict import OrderedDict + except ImportError: + ordered_dict_defined = False + class ResourceTestCase(unittest.TestCase): def setUp(self): self.data = { "foo": "bar", } + if ordered_dict_defined: + self.data1 = OrderedDict(( + ("foo", "bar"), + ("foo2", "bar"), + ("foo1", "bar"), + )) - def test_json_get_serializer(self): + def prepare_json_serializer(self): s = slumber.serialize.Serializer() serializer = None @@ -23,11 +38,25 @@ def test_json_get_serializer(self): serializer = s.get_serializer(content_type=content_type) self.assertEqual(type(serializer), slumber.serialize.JsonSerializer, "content_type %s should produce a JsonSerializer") + return serializer + + def test_json_get_serializer(self): + serializer = self.prepare_json_serializer() result = serializer.dumps(self.data) self.assertEqual(result, '{"foo": "bar"}') self.assertEqual(self.data, serializer.loads(result)) + def test_json_get_serializer_ordereddict(self): + if not ordered_dict_defined: # skip this test if OrderedDict is not loaded + return + + serializer = self.prepare_json_serializer() + + result = serializer.dumps(self.data1) + self.assertEqual(result, '{"foo": "bar", "foo2": "bar", "foo1": "bar"}') + self.assertEqual(self.data1, serializer.loads(result)) + def test_yaml_get_serializer(self): s = slumber.serialize.Serializer()