We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
JSON output reordered by pydantic @validator
This isn't a big problem, but I'm wondering if it's possible to keep the JSON output key ordering unaffected by the presence of a Pydantic `@validator(...)`? I like consistency. 🤷‍♂️

I have this pydantic model structure:
```
class IngredientBase(BaseIngredientMixin):
    name: str = None
    unit: str = None
    unit_price: decimal.Decimal = None
    flavour_warning: bool = None

    @validator('unit')
    def valid_units_only(cls, v):
        choices = set(SingleIngredientTable.unit_choices.keys())
        if v and v not in choices:
            raise ValueError(f'must be one of {choices}')
        return v


class IngredientIn(IngredientBase):
    pass


class IngredientNew(IngredientIn):
    name: str = ...
    unit: str = ...
    unit_price: decimal.Decimal = ...


class IngredientOut(IngredientBase, TestModelMixin, TimestampModelMixin, IDModelMixin):
    pass
```

This will produce:
```
{
  "unit": "IU",
  "id": "sing_qOYSyqZhfOcJKHsfVz7tnfP6M",
  "created": 1571357369,
  "updated": 1571418480,
  "is_test": false,
  "name": "Vitamin C",
  "unit_price": 10.568536363534536,
  "flavour_warning": false
}
```
Without the validator, it produces what I would expect:
```
{
  "id": "sing_qOYSyqZhfOcJKHsfVz7tnfP6M",
  "created": 1571357369,
  "updated": 1571418480,
  "is_test": false,
  "name": "Vitamin C",
  "unit": "IU",
  "unit_price": 10.568536363534536,
  "flavour_warning": false
}
```

How can I continue to use `@validator`s and maintain the expected JSON key ordering?

**Edit**: I can pull out the validator into a 'mixin' class that I apply ONLY to the `IngredientIn` and `IngredientNew` models (leaving `IngredientOut` untouched). But is that my only path here?
JSON output reordered by pydantic @validator
This isn't a big problem, but I'm wondering if it's possible to keep the JSON output key ordering unaffected by the presence of a Pydantic `@validator(...)`? I like consistency. 🤷‍♂️

I have this pydantic model structure:
```
class IngredientBase(BaseIngredientMixin):
    name: str = None
    unit: str = None
    unit_price: decimal.Decimal = None
    flavour_warning: bool = None

    @validator('unit')
    def valid_units_only(cls, v):
        choices = set(SingleIngredientTable.unit_choices.keys())
        if v and v not in choices:
            raise ValueError(f'must be one of {choices}')
        return v


class IngredientIn(IngredientBase):
    pass


class IngredientNew(IngredientIn):
    name: str = ...
    unit: str = ...
    unit_price: decimal.Decimal = ...


class IngredientOut(IngredientBase, TestModelMixin, TimestampModelMixin, IDModelMixin):
    pass
```

This will produce:
```
{
  "unit": "IU",
  "id": "sing_qOYSyqZhfOcJKHsfVz7tnfP6M",
  "created": 1571357369,
  "updated": 1571418480,
  "is_test": false,
  "name": "Vitamin C",
  "unit_price": 10.568536363534536,
  "flavour_warning": false
}
```
Without the validator, it produces what I would expect:
```
{
  "id": "sing_qOYSyqZhfOcJKHsfVz7tnfP6M",
  "created": 1571357369,
  "updated": 1571418480,
  "is_test": false,
  "name": "Vitamin C",
  "unit": "IU",
  "unit_price": 10.568536363534536,
  "flavour_warning": false
}
```

How can I continue to use `@validator`s and maintain the expected JSON key ordering?

**Edit**: I can pull out the validator into a 'mixin' class that I apply ONLY to the `IngredientIn` and `IngredientNew` models (leaving `IngredientOut` untouched). But is that my only path here?

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `fastapi/utils.py`
Content:
```
1 import re
2 from dataclasses import is_dataclass
3 from typing import Any, Dict, List, Sequence, Set, Type, cast
4 
5 from fastapi import routing
6 from fastapi.openapi.constants import REF_PREFIX
7 from pydantic import BaseConfig, BaseModel, Schema, create_model
8 from pydantic.fields import Field
9 from pydantic.schema import get_flat_models_from_fields, model_process_schema
10 from pydantic.utils import lenient_issubclass
11 from starlette.routing import BaseRoute
12 
13 
14 def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]:
15     body_fields_from_routes: List[Field] = []
16     responses_from_routes: List[Field] = []
17     for route in routes:
18         if getattr(route, "include_in_schema", None) and isinstance(
19             route, routing.APIRoute
20         ):
21             if route.body_field:
22                 assert isinstance(
23                     route.body_field, Field
24                 ), "A request body must be a Pydantic Field"
25                 body_fields_from_routes.append(route.body_field)
26             if route.response_field:
27                 responses_from_routes.append(route.response_field)
28             if route.response_fields:
29                 responses_from_routes.extend(route.response_fields.values())
30     flat_models = get_flat_models_from_fields(
31         body_fields_from_routes + responses_from_routes, known_models=set()
32     )
33     return flat_models
34 
35 
36 def get_model_definitions(
37     *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str]
38 ) -> Dict[str, Any]:
39     definitions: Dict[str, Dict] = {}
40     for model in flat_models:
41         m_schema, m_definitions, m_nested_models = model_process_schema(
42             model, model_name_map=model_name_map, ref_prefix=REF_PREFIX
43         )
44         definitions.update(m_definitions)
45         model_name = model_name_map[model]
46         definitions[model_name] = m_schema
47     return definitions
48 
49 
50 def get_path_param_names(path: str) -> Set[str]:
51     return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
52 
53 
54 def create_cloned_field(field: Field) -> Field:
55     original_type = field.type_
56     if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"):
57         original_type = original_type.__pydantic_model__  # type: ignore
58     use_type = original_type
59     if lenient_issubclass(original_type, BaseModel):
60         original_type = cast(Type[BaseModel], original_type)
61         use_type = create_model(
62             original_type.__name__,
63             __config__=original_type.__config__,
64             __validators__=original_type.__validators__,  # type: ignore
65         )
66         for f in original_type.__fields__.values():
67             use_type.__fields__[f.name] = f
68     new_field = Field(
69         name=field.name,
70         type_=use_type,
71         class_validators={},
72         default=None,
73         required=False,
74         model_config=BaseConfig,
75         schema=Schema(None),
76     )
77     new_field.has_alias = field.has_alias
78     new_field.alias = field.alias
79     new_field.class_validators = field.class_validators
80     new_field.default = field.default
81     new_field.required = field.required
82     new_field.model_config = field.model_config
83     new_field.schema = field.schema
84     new_field.allow_none = field.allow_none
85     new_field.validate_always = field.validate_always
86     if field.sub_fields:
87         new_field.sub_fields = [
88             create_cloned_field(sub_field) for sub_field in field.sub_fields
89         ]
90     if field.key_field:
91         new_field.key_field = create_cloned_field(field.key_field)
92     new_field.validators = field.validators
93     new_field.whole_pre_validators = field.whole_pre_validators
94     new_field.whole_post_validators = field.whole_post_validators
95     new_field.parse_json = field.parse_json
96     new_field.shape = field.shape
97     new_field._populate_validators()
98     return new_field
99 
100 
101 def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str:
102     operation_id = name + path
103     operation_id = operation_id.replace("{", "_").replace("}", "_").replace("/", "_")
104     operation_id = operation_id + "_" + method.lower()
105     return operation_id
106
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/fastapi/utils.py b/fastapi/utils.py
--- a/fastapi/utils.py
+++ b/fastapi/utils.py
@@ -59,12 +59,11 @@
     if lenient_issubclass(original_type, BaseModel):
         original_type = cast(Type[BaseModel], original_type)
         use_type = create_model(
-            original_type.__name__,
-            __config__=original_type.__config__,
-            __validators__=original_type.__validators__,  # type: ignore
+            original_type.__name__, __config__=original_type.__config__
         )
         for f in original_type.__fields__.values():
             use_type.__fields__[f.name] = f
+        use_type.__validators__ = original_type.__validators__
     new_field = Field(
         name=field.name,
         type_=use_type,

{"golden_diff": "diff --git a/fastapi/utils.py b/fastapi/utils.py\n--- a/fastapi/utils.py\n+++ b/fastapi/utils.py\n@@ -59,12 +59,11 @@\n     if lenient_issubclass(original_type, BaseModel):\n         original_type = cast(Type[BaseModel], original_type)\n         use_type = create_model(\n-            original_type.__name__,\n-            __config__=original_type.__config__,\n-            __validators__=original_type.__validators__,  # type: ignore\n+            original_type.__name__, __config__=original_type.__config__\n         )\n         for f in original_type.__fields__.values():\n             use_type.__fields__[f.name] = f\n+        use_type.__validators__ = original_type.__validators__\n     new_field = Field(\n         name=field.name,\n         type_=use_type,\n", "issue": "JSON output reordered by pydantic @validator\nThis isn't a big problem, but I'm wondering if it's possible to keep the JSON output key ordering unaffected by the presence of a Pydantic `@validator(...)`? I like consistency. \ud83e\udd37\u200d\u2642\ufe0f\r\n\r\nI have this pydantic model structure:\r\n```\r\nclass IngredientBase(BaseIngredientMixin):\r\n    name: str = None\r\n    unit: str = None\r\n    unit_price: decimal.Decimal = None\r\n    flavour_warning: bool = None\r\n\r\n    @validator('unit')\r\n    def valid_units_only(cls, v):\r\n        choices = set(SingleIngredientTable.unit_choices.keys())\r\n        if v and v not in choices:\r\n            raise ValueError(f'must be one of {choices}')\r\n        return v\r\n\r\n\r\nclass IngredientIn(IngredientBase):\r\n    pass\r\n\r\n\r\nclass IngredientNew(IngredientIn):\r\n    name: str = ...\r\n    unit: str = ...\r\n    unit_price: decimal.Decimal = ...\r\n\r\n\r\nclass IngredientOut(IngredientBase, TestModelMixin, TimestampModelMixin, IDModelMixin):\r\n    pass\r\n```\r\n\r\nThis will produce:\r\n```\r\n{\r\n  \"unit\": \"IU\",\r\n  \"id\": \"sing_qOYSyqZhfOcJKHsfVz7tnfP6M\",\r\n  \"created\": 1571357369,\r\n  \"updated\": 1571418480,\r\n  \"is_test\": false,\r\n  \"name\": \"Vitamin C\",\r\n  \"unit_price\": 10.568536363534536,\r\n  \"flavour_warning\": false\r\n}\r\n```\r\nWithout the validator, it produces what I would expect:\r\n```\r\n{\r\n  \"id\": \"sing_qOYSyqZhfOcJKHsfVz7tnfP6M\",\r\n  \"created\": 1571357369,\r\n  \"updated\": 1571418480,\r\n  \"is_test\": false,\r\n  \"name\": \"Vitamin C\",\r\n  \"unit\": \"IU\",\r\n  \"unit_price\": 10.568536363534536,\r\n  \"flavour_warning\": false\r\n}\r\n```\r\n\r\nHow can I continue to use `@validator`s and maintain the expected JSON key ordering?\r\n\r\n**Edit**: I can pull out the validator into a 'mixin' class that I apply ONLY to the `IngredientIn` and `IngredientNew` models (leaving `IngredientOut` untouched). But is that my only path here?\nJSON output reordered by pydantic @validator\nThis isn't a big problem, but I'm wondering if it's possible to keep the JSON output key ordering unaffected by the presence of a Pydantic `@validator(...)`? I like consistency. \ud83e\udd37\u200d\u2642\ufe0f\r\n\r\nI have this pydantic model structure:\r\n```\r\nclass IngredientBase(BaseIngredientMixin):\r\n    name: str = None\r\n    unit: str = None\r\n    unit_price: decimal.Decimal = None\r\n    flavour_warning: bool = None\r\n\r\n    @validator('unit')\r\n    def valid_units_only(cls, v):\r\n        choices = set(SingleIngredientTable.unit_choices.keys())\r\n        if v and v not in choices:\r\n            raise ValueError(f'must be one of {choices}')\r\n        return v\r\n\r\n\r\nclass IngredientIn(IngredientBase):\r\n    pass\r\n\r\n\r\nclass IngredientNew(IngredientIn):\r\n    name: str = ...\r\n    unit: str = ...\r\n    unit_price: decimal.Decimal = ...\r\n\r\n\r\nclass IngredientOut(IngredientBase, TestModelMixin, TimestampModelMixin, IDModelMixin):\r\n    pass\r\n```\r\n\r\nThis will produce:\r\n```\r\n{\r\n  \"unit\": \"IU\",\r\n  \"id\": \"sing_qOYSyqZhfOcJKHsfVz7tnfP6M\",\r\n  \"created\": 1571357369,\r\n  \"updated\": 1571418480,\r\n  \"is_test\": false,\r\n  \"name\": \"Vitamin C\",\r\n  \"unit_price\": 10.568536363534536,\r\n  \"flavour_warning\": false\r\n}\r\n```\r\nWithout the validator, it produces what I would expect:\r\n```\r\n{\r\n  \"id\": \"sing_qOYSyqZhfOcJKHsfVz7tnfP6M\",\r\n  \"created\": 1571357369,\r\n  \"updated\": 1571418480,\r\n  \"is_test\": false,\r\n  \"name\": \"Vitamin C\",\r\n  \"unit\": \"IU\",\r\n  \"unit_price\": 10.568536363534536,\r\n  \"flavour_warning\": false\r\n}\r\n```\r\n\r\nHow can I continue to use `@validator`s and maintain the expected JSON key ordering?\r\n\r\n**Edit**: I can pull out the validator into a 'mixin' class that I apply ONLY to the `IngredientIn` and `IngredientNew` models (leaving `IngredientOut` untouched). But is that my only path here?\n", "before_files": [{"content": "import re\nfrom dataclasses import is_dataclass\nfrom typing import Any, Dict, List, Sequence, Set, Type, cast\n\nfrom fastapi import routing\nfrom fastapi.openapi.constants import REF_PREFIX\nfrom pydantic import BaseConfig, BaseModel, Schema, create_model\nfrom pydantic.fields import Field\nfrom pydantic.schema import get_flat_models_from_fields, model_process_schema\nfrom pydantic.utils import lenient_issubclass\nfrom starlette.routing import BaseRoute\n\n\ndef get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]:\n    body_fields_from_routes: List[Field] = []\n    responses_from_routes: List[Field] = []\n    for route in routes:\n        if getattr(route, \"include_in_schema\", None) and isinstance(\n            route, routing.APIRoute\n        ):\n            if route.body_field:\n                assert isinstance(\n                    route.body_field, Field\n                ), \"A request body must be a Pydantic Field\"\n                body_fields_from_routes.append(route.body_field)\n            if route.response_field:\n                responses_from_routes.append(route.response_field)\n            if route.response_fields:\n                responses_from_routes.extend(route.response_fields.values())\n    flat_models = get_flat_models_from_fields(\n        body_fields_from_routes + responses_from_routes, known_models=set()\n    )\n    return flat_models\n\n\ndef get_model_definitions(\n    *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str]\n) -> Dict[str, Any]:\n    definitions: Dict[str, Dict] = {}\n    for model in flat_models:\n        m_schema, m_definitions, m_nested_models = model_process_schema(\n            model, model_name_map=model_name_map, ref_prefix=REF_PREFIX\n        )\n        definitions.update(m_definitions)\n        model_name = model_name_map[model]\n        definitions[model_name] = m_schema\n    return definitions\n\n\ndef get_path_param_names(path: str) -> Set[str]:\n    return {item.strip(\"{}\") for item in re.findall(\"{[^}]*}\", path)}\n\n\ndef create_cloned_field(field: Field) -> Field:\n    original_type = field.type_\n    if is_dataclass(original_type) and hasattr(original_type, \"__pydantic_model__\"):\n        original_type = original_type.__pydantic_model__  # type: ignore\n    use_type = original_type\n    if lenient_issubclass(original_type, BaseModel):\n        original_type = cast(Type[BaseModel], original_type)\n        use_type = create_model(\n            original_type.__name__,\n            __config__=original_type.__config__,\n            __validators__=original_type.__validators__,  # type: ignore\n        )\n        for f in original_type.__fields__.values():\n            use_type.__fields__[f.name] = f\n    new_field = Field(\n        name=field.name,\n        type_=use_type,\n        class_validators={},\n        default=None,\n        required=False,\n        model_config=BaseConfig,\n        schema=Schema(None),\n    )\n    new_field.has_alias = field.has_alias\n    new_field.alias = field.alias\n    new_field.class_validators = field.class_validators\n    new_field.default = field.default\n    new_field.required = field.required\n    new_field.model_config = field.model_config\n    new_field.schema = field.schema\n    new_field.allow_none = field.allow_none\n    new_field.validate_always = field.validate_always\n    if field.sub_fields:\n        new_field.sub_fields = [\n            create_cloned_field(sub_field) for sub_field in field.sub_fields\n        ]\n    if field.key_field:\n        new_field.key_field = create_cloned_field(field.key_field)\n    new_field.validators = field.validators\n    new_field.whole_pre_validators = field.whole_pre_validators\n    new_field.whole_post_validators = field.whole_post_validators\n    new_field.parse_json = field.parse_json\n    new_field.shape = field.shape\n    new_field._populate_validators()\n    return new_field\n\n\ndef generate_operation_id_for_path(*, name: str, path: str, method: str) -> str:\n    operation_id = name + path\n    operation_id = operation_id.replace(\"{\", \"_\").replace(\"}\", \"_\").replace(\"/\", \"_\")\n    operation_id = operation_id + \"_\" + method.lower()\n    return operation_id\n", "path": "fastapi/utils.py"}], "after_files": [{"content": "import re\nfrom dataclasses import is_dataclass\nfrom typing import Any, Dict, List, Sequence, Set, Type, cast\n\nfrom fastapi import routing\nfrom fastapi.openapi.constants import REF_PREFIX\nfrom pydantic import BaseConfig, BaseModel, Schema, create_model\nfrom pydantic.fields import Field\nfrom pydantic.schema import get_flat_models_from_fields, model_process_schema\nfrom pydantic.utils import lenient_issubclass\nfrom starlette.routing import BaseRoute\n\n\ndef get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]:\n    body_fields_from_routes: List[Field] = []\n    responses_from_routes: List[Field] = []\n    for route in routes:\n        if getattr(route, \"include_in_schema\", None) and isinstance(\n            route, routing.APIRoute\n        ):\n            if route.body_field:\n                assert isinstance(\n                    route.body_field, Field\n                ), \"A request body must be a Pydantic Field\"\n                body_fields_from_routes.append(route.body_field)\n            if route.response_field:\n                responses_from_routes.append(route.response_field)\n            if route.response_fields:\n                responses_from_routes.extend(route.response_fields.values())\n    flat_models = get_flat_models_from_fields(\n        body_fields_from_routes + responses_from_routes, known_models=set()\n    )\n    return flat_models\n\n\ndef get_model_definitions(\n    *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str]\n) -> Dict[str, Any]:\n    definitions: Dict[str, Dict] = {}\n    for model in flat_models:\n        m_schema, m_definitions, m_nested_models = model_process_schema(\n            model, model_name_map=model_name_map, ref_prefix=REF_PREFIX\n        )\n        definitions.update(m_definitions)\n        model_name = model_name_map[model]\n        definitions[model_name] = m_schema\n    return definitions\n\n\ndef get_path_param_names(path: str) -> Set[str]:\n    return {item.strip(\"{}\") for item in re.findall(\"{[^}]*}\", path)}\n\n\ndef create_cloned_field(field: Field) -> Field:\n    original_type = field.type_\n    if is_dataclass(original_type) and hasattr(original_type, \"__pydantic_model__\"):\n        original_type = original_type.__pydantic_model__  # type: ignore\n    use_type = original_type\n    if lenient_issubclass(original_type, BaseModel):\n        original_type = cast(Type[BaseModel], original_type)\n        use_type = create_model(\n            original_type.__name__, __config__=original_type.__config__\n        )\n        for f in original_type.__fields__.values():\n            use_type.__fields__[f.name] = f\n        use_type.__validators__ = original_type.__validators__\n    new_field = Field(\n        name=field.name,\n        type_=use_type,\n        class_validators={},\n        default=None,\n        required=False,\n        model_config=BaseConfig,\n        schema=Schema(None),\n    )\n    new_field.has_alias = field.has_alias\n    new_field.alias = field.alias\n    new_field.class_validators = field.class_validators\n    new_field.default = field.default\n    new_field.required = field.required\n    new_field.model_config = field.model_config\n    new_field.schema = field.schema\n    new_field.allow_none = field.allow_none\n    new_field.validate_always = field.validate_always\n    if field.sub_fields:\n        new_field.sub_fields = [\n            create_cloned_field(sub_field) for sub_field in field.sub_fields\n        ]\n    if field.key_field:\n        new_field.key_field = create_cloned_field(field.key_field)\n    new_field.validators = field.validators\n    new_field.whole_pre_validators = field.whole_pre_validators\n    new_field.whole_post_validators = field.whole_post_validators\n    new_field.parse_json = field.parse_json\n    new_field.shape = field.shape\n    new_field._populate_validators()\n    return new_field\n\n\ndef generate_operation_id_for_path(*, name: str, path: str, method: str) -> str:\n    operation_id = name + path\n    operation_id = operation_id.replace(\"{\", \"_\").replace(\"}\", \"_\").replace(\"/\", \"_\")\n    operation_id = operation_id + \"_\" + method.lower()\n    return operation_id\n", "path": "fastapi/utils.py"}]}