在初始化Request的时候:
1 def initialize_request(self, request, *args, **kwargs): 2 """ 3 Returns the initial request object. 4 """ 5 parser_context = self.get_parser_context(request) 6 7 return Request( 8 request, 9 parsers=self.get_parsers(), #添加解析器 10 authenticators=self.get_authenticators(), 11 negotiator=self.get_content_negotiator(), 12 parser_context=parser_context 13 )
内置的json解析器可以在视图类中添加:如parser_classes = [JSONParser,]
1 class JSONParser(BaseParser): 2 """ 3 Parses JSON-serialized data. 4 """ 5 media_type = 'application/json' 6 renderer_class = renderers.JSONRenderer 7 strict = api_settings.STRICT_JSON 8 9 def parse(self, stream, media_type=None, parser_context=None): 10 """ 11 Parses the incoming bytestream as JSON and returns the resulting data. 12 """ 13 parser_context = parser_context or {} 14 encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) 15 16 try: 17 decoded_stream = codecs.getreader(encoding)(stream) 18 parse_constant = json.strict_constant if self.strict else None 19 return json.load(decoded_stream, parse_constant=parse_constant) 20 except ValueError as exc: 21 raise ParseError('JSON parse error - %s' % six.text_type(exc))