Google Cloud端点以JSON中的字符串形式返回Java
我使用的是Google App Engine最新版本1.9.30,并且按如下所示定义了我的云终结点
I am using google app engine latest version 1.9.30 and I define my cloud endpoint as follows
@Api(name="app", version="v1", transformers={EndpointDateTransformer.class})
public class MyEndpoints {
@ApiMethod(name="dummy", path="dummy", httpMethod=HttpMethod.GET)
public Map<String, Object> dummy(){
Map<String, Object> dummy = Maps.newHashMap();
dummy.put("date", DateUtil.getCurrentTimestamp());
dummy.put("number", 5L);
return dummy;
}
}
此处EndpointDateTransformer将Date转换为Long值,并且来自端点的JSON响应为
here EndpointDateTransformer converts Date to Long value and the JSON response from endpoint is
{
"number": "5",
"date": "1452751174672"
}
但是如果我将5L更改为5,那么我会看到JSON响应
But if I change that 5L to 5 then I see JSON response as
{
"number": 5,
"date": "1452751174672"
}
为什么云端点将Long值转换为JSON中的字符串.当我使用旧版App Engine 1.9.19时,它曾经可以工作.以及在JSON上的长渲染.我在这里想念什么吗?
Why cloud endpoints converting Long values as string in JSON. When I was working on old app engine versions 1.9.19 it used to work. Long rendered as long on JSON as well. Am I missing anything here?
JSON是JavaScript对象符号,实际上是有效的Javascript.因此,它应该遵循javascript标准.
JSON is JavaScript Object Notation, it's a valid Javascript actually. So it should follow javascript standards.
JavaScript的编号是54位,从-(2^53 - 1)
到(2^53 - 1)
.但是Java的long是64位数字,从-2^63
到2^63-1
.
Javascript's Number is 54 bit number, from -(2^53 - 1)
to (2^53 - 1)
. But Java's long is 64 bit number, from -2^63
to 2^63-1
.
查看区别:
Java Long Max = 9223372036854775807
Javascript Number Max = 9007199254740992
您根本无法将Java Long转换为Javascript Number,因为它不适用于所有值.因此,将使用字符串表示形式.
You simply cannot convert Java Long to Javascript Number because it doesn't work for all values. So a string representation is used instead.
您有两种可能的解决方案:
You have two possible solutions:
- 将您的价值定义为
Integer
- 使用具有自定义转换器的实体对象,请参见 https://cloud .google.com/appengine/docs/java/endpoints/annotations#apitransformer
- define your value as
Integer
- use an entity object with custom transformer, see https://cloud.google.com/appengine/docs/java/endpoints/annotations#apitransformer
或者如果您真的想要日期,最好在UTC时区将其格式化为yyyy-MM-dd\'T\'HH:mm:ss
.它与Javascript日期格式兼容.
Or if you really want Date, it's better to format it as yyyy-MM-dd\'T\'HH:mm:ss
within UTC timezone. It's compatible with Javascript date format.
规格:
- Javascript- https://developer.mozilla. org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
- Java- https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
- Javascript日期- https://developer.mozilla .org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date
- Javascript - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
- Java - https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
- Javascript Date - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date