0

我正在使用Google Endpoints Framework和Python(https://cloud.google.com/endpoints/docs/frameworks/python/get-started-frameworks-python),並一直在使用它構建REST API。使用Python中的Google Cloud Endpoints Framework返回JSON數組作爲響應

我能夠在像響應返回JSON對象(字典):

{ 
    "items":[ 
     { 
      "id": "brand_1_id", 
      "name": "Brand 1" 
     }, 
     { 
      "id": "brand_2_id", 
      "name": "Brand 2" 
     } 
    ] 
} 

然而,我無法返回JSON數組(列表)作爲樣應答:

[ { 「ID」: 「brand_1_id」, 「名稱」: 「品牌1」 },{ 「ID」: 「brand_2_id」, 「名稱」: 「品牌2」 } ]

以下是我一直使用到返回響應

下面是類創建發送響應代碼段:

class BrandResponse(messages.Message): 
    id=messages.StringField(1, required=True) 
    brandName = messages.StringField(2, required=True) 
    brandEmail=messages.StringField(3, required=True) 
    brandPhone=messages.StringField(4,required=True) 
    brandAddress=messages.StringField(5,required=True) 
    brandCity=messages.StringField(6,required=True) 
    brandState=messages.StringField(7,required=True) 
    brandCountry=messages.StringField(8,required=True) 
    brandPostalCode=messages.StringField(9,required=True) 

class MultipleBrandResponse(messages.Message): 
    items=messages.MessageField(BrandResponse,1,repeated=True) 

以下是處理請求的方法:

@endpoints.method(
     MULTIPLE_BRAND_PAGINATED_CONTAINER, 
     MultipleBrandResponse, 
     path='brand', 
     http_method='GET', 
     name='Get Brands', 
     audiences=firebaseAudience 
    ) 
    def getBrands(self,request): 
     brandResponse=[] 

     query = BrandDB.query() 
     brands = query.fetch(request.limit, offset=request.start) 
     for brand in brands: 
      brandResponse.append(BrandResponse(
      id=brand.key.urlsafe(), 
      brandName=brand.name, 
      brandAddress=brand.address, 
      brandCity=brand.city, 
      brandState=brand.state, 
      brandCountry=brand.country, 
      brandPostalCode=brand.postalCode, 
      brandPhone=brand.phone, 
      brandEmail=brand.email)) 

     print("Brand count: "+str(brandResponse.count)) 

     if len(brandResponse) == 0: 
      raise endpoints.NotFoundException("No brands") 

     return MultipleBrandResponse(items=brandResponse) 

任何想法如何返回JSON數組直接而不是在一個JSON對象內部封裝一個鍵。

回答

1

該框架是圍繞返回協議緩衝區消息而非JSON而設計的。你可能已經指定了一個結構匹配的消息,很難說沒有看到你的代碼。

+0

我已更新該問題以包含實際的代碼。 – Tejas

+0

您沒有使用JSON對象。您正在使用協議緩衝區消息; MultipleBrandResponse是包含一個字段的消息,其中包含BrandResponse消息的列表。協議緩衝區響應的「根」必須是單個消息,而不是消息列表。 –

+0

認爲你是對的。因此,使用Protocol Buffers並創建REST API,無法獲取多個消息,因此無法獲取JSON數組作爲響應。 – Tejas

相關問題