问题
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;
}
}
here EndpointDateTransformer converts Date to Long value and the JSON response from endpoint is
{
"number": "5",
"date": "1452751174672"
}
But if I change that 5L to 5 then I see JSON response as
{
"number": 5,
"date": "1452751174672"
}
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?
回答1:
JSON is JavaScript Object Notation, it's a valid Javascript actually. So it should follow javascript standards.
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
.
See difference:
Java Long Max = 9223372036854775807
Javascript Number Max = 9007199254740992
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:
- define your value as
Integer
- use an entity object with custom transformer, see https://cloud.google.com/appengine/docs/java/endpoints/annotations#apitransformer
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.
Specs:
- 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
来源:https://stackoverflow.com/questions/34783049/google-cloud-endpoints-returning-java-long-as-string-in-json