如何在Google Endpoints中返回json对象 [英] How to return a json object in Google Endpoints

查看:91
本文介绍了如何在Google Endpoints中返回json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在做的方式是我有一个带有字符串消息的响应类并返回一个json字符串。在客户端,我解析字符串以将其用作对象。我想知道我们是否可以简单地返回一个json对象,而不是通过解析部分。

The way I'm doing right now is I have a response class with a string message and return a json string. On the client side, I parse the string to use it as a object. I was wondering if we can simply return a json object rather going through the parsing part

现在我使用的是:

class Response(messages.Message):
  resp = messages.StringField(1)

在客户端我会得到像这样的东西

on the client side I will get something like this

{resp: "{"message": "sucess", "some_data":"data"}"}

resp 字符串。然而,我想要的回应是

and I parse the resp string. However, my desired response will be

{message: "sucess", some_data:"data"}

编辑:我意识到我们在消息类下声明每个键的选项,但是我的问题更多地是返回任何泛型json object

Im aware of the option where we state each key under the message class, But my question is more towards returning any generic json object

推荐答案

您可以直接在响应类中定义'message'和'some_data'。例如:

You can define 'message' and 'some_data' on the response class directly. eg:

    class Response(messages.Message):
        message = messages.StringField(1)
        some_data = messages.StringField(2)

    jsonDict = {"message": "success", "some_data": "data"}
    return Response(**jsonDict )

如果您只有json字符串,则需要先转换为字典:

If you only have a json string, you will need to convert to a dictionary first:

jsonDict = json.loads(jsonString)

这篇关于如何在Google Endpoints中返回json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆