我想使用django自定义json格式

时间:2017-02-10 08:29:39

标签: json django format retrofit

Django对我来说很新,我想要自定义json响应。 我尝试使用Android app retrofit从服务器获得响应。 服务器响应准确。 我需要匹配json格式请帮帮我,谢谢

我得到了像

这样的json格式
  {
    "username": "admin",
    "token": "xxx"
}

但我想要

responseCode{
   responseCode:xxx,
   ResponseData:
         {token:xxx,username:xxx}
    }

返回json格式数据的代码

class UserLoginSerializer(serializers.ModelSerializer):
token = serializers.CharField(allow_blank = True , read_only = True)
username = serializers.CharField(required = False , allow_blank=True)
#email = serializers.EmailField(label="Email Adress",required = False, allow_blank=True)
class Meta:
    model = User
    fields = [
        'username',
        #'email',
        'password',
        'token',



    ]
    extra_kwargs ={"password":
                    {"write_only":True  
                    }
    }
def validate(self, data):
    user_obj = None
    #email = data.get('email', None)
    username = data.get("username", None)
    password = data["password"]
    if not username:
            raise ValidationError("A username or email is required to login")

    user=User.objects.filter(
            #Q(email=email)|
            Q(username=username)

        ).distinct()
    #user = user.exclude(email=None)
    if user.exists() and user.count() == 1 :
        user_obj = user.first()
    else:
        raise ValidationError("username not valid.")

    if user_obj:
        if not user_obj.check_password(password):
            raise ValidationError("Incorrect credentials please try again")


    #token = Token.objects.get_or_create(user=user_obj)
    token, created = Token.objects.get_or_create(user=user_obj)

    data["token"] = token.key
    data["username"] = user_obj


    return data

我试过这样的事情

# responseCode = {}
# responseData = {}

# responseData['token'] = token.key
# responseData['username'] = user_obj
# responseCode['responseData'] = responseData
# data["responseCode"] = responseCode

但不行,请帮帮我

2 个答案:

答案 0 :(得分:0)

responseCode{
   responseCode:xxx,
   ResponseData:
         {token:xxx,username:xxx}
    }

不是有效的json文件。

你应该这样:

data["responseCode"]={
   "responseCode":"xxx",
   "ResponseData":
         {
             token:token.key,
             username:user_obj
          }
    }

然后,当您调用数据时,它将返回

responseCode:{
   responseCode:xxx,
   ResponseData:
         {token:xxx,username:xxx}
    }

答案 1 :(得分:-1)

有效的JSON格式如下:

{
    key1 : value1,
    key2 : value2,
}

我们也可以拥有嵌套值。所以,嵌套值看起来像

{
    key1 : {
              key_nested1 : value,
              key_nested2 : value
            },
    key2 : value
 }

现在,一旦您理解了这一点,我们就可以轻松地以JSON格式转换所需的值。所以,在Python中,我们使用字典来创建这个结构,就像你在代码中尝试过一样。

JSONFormat = {}  #corresponds to empty json file

#now we need to insert key value pairs
JSONFormat["ResponseCode"]= "Fill your response code here"

#this is how our json will look now
#{
#     ResponseCode : "Fill your reponse code here"
#}

现在,ResponseData有一个嵌套字典作为其值 所以我们需要做这两件事

  1. 创建字典
  2. 将该字典作为键“ResponseData”的值,如下所示

        ResponseDataValue = { }        #create the dictionary
        ResponseDataValue["Token"] = "Your Token Here"
        ResponseDataValue["Username"] = "Your User Name"
    
        #now we take this value and place it against out json_format dict
    
        JSONFormat["ResponseData"] = ResponseDataValue
    
  3. 所以最后你可以得到你想要的格式

    {
         ResponseCode :"Your Code",
         ResponseData : {
                            Token : "Your Token",
                            Username : "the username"
                        }
    }