下面列出了怎么用com.google.gson.JsonDeserializationContext的API类实例代码及写法,或者点击链接到github查看源代码。
private static ReflexActionLog convertLg(JsonObject lg, JsonDeserializationContext context) {
ReflexActionLog.Level l = ReflexActionLog.Level.valueOf(lg.get("l").getAsString());
String m = lg.get("m").getAsString();
JsonElement jargsc = lg.get("a");
if (jargsc != null && jargsc.isJsonArray()) {
JsonArray jargs = jargsc.getAsJsonArray();
ImmutableList.Builder<ReflexActionLog.Arg> bld = ImmutableList.builder();
for (JsonElement elem : jargs) {
bld.add(ReflexActionLog.Arg.valueOf(elem.getAsString()));
}
return new ReflexActionLog(l, m, bld.build());
} else {
return new ReflexActionLog(l, m, ImmutableList.<ReflexActionLog.Arg>of());
}
}
private static ReflexActionAlertmeLifesign convertAlAction(JsonObject al, JsonDeserializationContext context) {
ReflexActionAlertmeLifesign.Type a = ReflexActionAlertmeLifesign.Type.valueOf(al.get("a").getAsString());
Double m = null;
Double n = null;
JsonElement me = al.get("m");
if (me != null && !me.isJsonNull()) {
m = me.getAsDouble();
}
JsonElement ne = al.get("n");
if (ne != null && !ne.isJsonNull()) {
n = ne.getAsDouble();
}
if (m != null && n != null) {
return new ReflexActionAlertmeLifesign(a,m,n);
} else {
return new ReflexActionAlertmeLifesign(a);
}
}
@Override
public ClientMessage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject src = json.getAsJsonObject();
if(src.isJsonNull()) {
return null;
}
try {
Map<String,Object> headers = context.deserialize(src.get(ATTR_HEADERS), new TypeToken<Map<String, Object>>(){}.getType());
MessageBody payload = context.deserialize(src.get(ATTR_PAYLOAD), MessageBody.class);
return ClientMessage.builder()
.withHeaders(headers)
.withPayload(payload)
.create();
}
catch(Exception e) {
throw new JsonParseException("Unable to create ClientMessage", e);
}
}
private static ReflexMatchZigbeeAttribute convertZa(JsonObject za, JsonDeserializationContext context) {
ReflexMatchZigbeeAttribute.Type type = ReflexMatchZigbeeAttribute.Type.valueOf(za.get("r").getAsString());
int pr = za.get("p").getAsInt();
int ep = za.get("e").getAsInt();
int cl = za.get("c").getAsInt();
int at = za.get("a").getAsInt();
Integer manuf = null;
Integer flags = null;
if (za.has("m")) {
manuf = za.get("m").getAsInt();
}
if (za.has("f")) {
flags = za.get("f").getAsInt();
}
ZclData vl = null;
JsonElement jvl = za.get("v");
if (jvl != null && !jvl.isJsonNull()) {
vl = ZclData.serde().fromBytes(ByteOrder.LITTLE_ENDIAN, Base64.decodeBase64(jvl.getAsString()));
}
return new ReflexMatchZigbeeAttribute(type, pr, ep, cl, at, vl, manuf, flags);
}
@Override
public ripe_md160_object deserialize(JsonElement json,
Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
ripe_md160_object ripemd160Object = new ripe_md160_object();
BaseEncoding encoding = BaseEncoding.base16().lowerCase();
byte[] byteContent = encoding.decode(json.getAsString());
if (byteContent.length != 20) {
throw new JsonParseException("ripe_md160_object size not correct.");
}
for (int i = 0; i < 5; ++i) {
ripemd160Object.hash[i] = ((byteContent[i * 4 + 3] & 0xff) << 24) |
((byteContent[i * 4 + 2] & 0xff) << 16) |
((byteContent[i * 4 + 1] & 0xff) << 8) |
((byteContent[i * 4 ] & 0xff));
}
return ripemd160Object;
}
@Override
public ClientMessage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject src = json.getAsJsonObject();
if(src.isJsonNull()) {
return null;
}
try {
String type = context.deserialize(src.get(ATTR_TYPE), String.class);
Map<String,Object> headers = context.deserialize(src.get(ATTR_HEADERS), TYPE_MAP.getType());
JsonObject payload = src.getAsJsonObject(ATTR_PAYLOAD);
EventDefinition event = definitions.getEvent(type);
Map<String, Object> attributes = deserializeEvent(payload.get(ATTR_ATTRIBUTES).getAsJsonObject(), event, context);
return
ClientMessage
.builder()
.withHeaders(headers)
.withType(type)
.withAttributes(attributes)
.create();
}
catch(Exception e) {
throw new JsonParseException("Unable to create ClientMessage", e);
}
}
@Override
public operation_type deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
operation_type operationType = new operation_type();
JsonArray jsonArray = json.getAsJsonArray();
operationType.nOperationType = jsonArray.get(0).getAsInt();
Type type = operations_map.getOperationObjectById(operationType.nOperationType);
if (type != null) {
operationType.operationContent = context.deserialize(jsonArray.get(1), type);
} else {
operationType.operationContent = context.deserialize(jsonArray.get(1), Object.class);
}
return operationType;
}
@Override
public Date deserialize(JsonElement json,
Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date dateResult = simpleDateFormat.parse(json.getAsString());
return dateResult;
} catch (ParseException e) {
e.printStackTrace();
throw new JsonParseException(e.getMessage() + json.getAsString());
}
}
@Override
public List<Pair<String, Long>> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
List<Pair<String, Long>> credTypes = new ArrayList<>();
for (JsonElement element : json.getAsJsonArray()) {
// all elements are arrays like ["public-key", "-7"]
JsonArray pair = element.getAsJsonArray();
String type = pair.get(0).getAsString();
try {
long alg = Long.parseLong(pair.get(1).getAsString());
credTypes.add(new Pair<>(type, alg));
} catch (NumberFormatException e) {
continue;
}
}
return credTypes;
}
@SuppressWarnings("unchecked")
@Override
public List deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// 如果这是一个数组
if (json.isJsonArray()) {
JsonArray array = json.getAsJsonArray();
// 获取 List 上的泛型
Type itemType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
List list = new ArrayList();
for (int i = 0; i < array.size(); i++) {
JsonElement element = array.get(i);
// 解析 List 中的条目对象
Object item = context.deserialize(element, itemType);
list.add(item);
}
return list;
} else {
// 和接口类型不符,直接返回 null
return null;
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public AlexaMessage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
JsonObject obj = json.getAsJsonObject();
Header h = context.deserialize(obj.get(SerDer.ATTR_HEADER), Header.class);
Class clazz = getPayloadClass(h.getName());
logger.debug("deserializing payload type {}", clazz);
Payload p = context.deserialize(obj.get(SerDer.ATTR_PAYLOAD), clazz);
if(p == null) {
logger.debug("got back null, returning new instance of {}", clazz);
p = (Payload) clazz.getConstructor().newInstance();
}
return new AlexaMessage(h, p);
} catch(Exception e) {
throw new JsonParseException(e);
}
}
private Map<String, Object> deserializeEvent(JsonObject object, EventDefinition event, JsonDeserializationContext ctx) {
if(event == null) {
return (Map<String, Object>)ctx.deserialize(object, TYPE_MAP.getType());
}
// TODO cache this
Map<String, ParameterDefinition> parameters = toMap(event.getParameters());
Map<String, Object> attributes = new HashMap<String, Object>();
for(Map.Entry<String, JsonElement> entry: object.entrySet()) {
String name = entry.getKey();
ParameterDefinition parameter = parameters.get(name);
Object value = deserializeAttribute(entry.getValue(), parameter != null ? parameter.getType() : null, ctx);
if(value != null) {
attributes.put(name, value);
}
}
return attributes;
}
private static ReflexMatchZigbeeIasZoneStatus convertZz(JsonObject zz, JsonDeserializationContext context) {
ReflexMatchZigbeeIasZoneStatus.Type type = ReflexMatchZigbeeIasZoneStatus.Type.valueOf(zz.get("r").getAsString());
int pr = zz.get("p").getAsInt();
int ep = zz.get("e").getAsInt();
int cl = zz.get("c").getAsInt();
int st = zz.get("s").getAsInt();
int us = zz.get("u").getAsInt();
int mx = zz.get("m").getAsInt();
Integer manuf = null;
Integer flags = null;
if (zz.has("v")) {
manuf = zz.get("v").getAsInt();
}
if (zz.has("f")) {
flags = zz.get("f").getAsInt();
}
return new ReflexMatchZigbeeIasZoneStatus(type, pr, ep, cl, st, us, mx, manuf, flags);
}
private static ReflexActionAlertmeLifesign convertAlAction(JsonObject al, JsonDeserializationContext context) {
ReflexActionAlertmeLifesign.Type a = ReflexActionAlertmeLifesign.Type.valueOf(al.get("a").getAsString());
Double m = null;
Double n = null;
JsonElement me = al.get("m");
if (me != null && !me.isJsonNull()) {
m = me.getAsDouble();
}
JsonElement ne = al.get("n");
if (ne != null && !ne.isJsonNull()) {
n = ne.getAsDouble();
}
if (m != null && n != null) {
return new ReflexActionAlertmeLifesign(a,m,n);
} else {
return new ReflexActionAlertmeLifesign(a);
}
}
private ReflexDriverDefinition parseV1(JsonObject drv, JsonDeserializationContext context) throws JsonParseException {
Version ver = Version.fromRepresentation(drv.get("v").getAsString());
String drvname = drv.get("n").getAsString();
String hash = drv.get("h").getAsString();
long offlineTimeout = drv.get("o").getAsLong();
ReflexRunMode mode = drv.get("m") == null ? ReflexRunMode.defaultMode() : ReflexRunMode.valueOf(drv.get("m").getAsString());
List<String> caps = context.deserialize(drv.get("c"), LIST_CAPS);
List<ReflexDefinition> reflexes = context.deserialize(drv.get("r"), LIST_REFLEXES);
ReflexDriverDFA dfa = null;
JsonElement jdfa = drv.get("d");
if (jdfa != null && !jdfa.isJsonNull()) {
dfa = context.deserialize(jdfa, REFLEX_DFA);
}
Set<String> capabilities = ImmutableSet.copyOf(caps);
return new ReflexDriverDefinition(drvname, ver, hash, offlineTimeout, capabilities, mode, reflexes, dfa);
}
private static ReflexMatchAlertmeLifesign convertAl(JsonObject al, JsonDeserializationContext context) {
int pr = al.get("p").getAsInt();
int ep = al.get("e").getAsInt();
int cl = al.get("c").getAsInt();
int st = al.get("s").getAsInt();
int us = al.get("u").getAsInt();
return new ReflexMatchAlertmeLifesign(pr, ep, cl, st, us);
}
@Override
public HpackHeaderField deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) {
JsonObject jsonObject = json.getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
if (entrySet.size() != 1) {
throw new JsonParseException("JSON Object has multiple entries: " + entrySet);
}
Map.Entry<String, JsonElement> entry = entrySet.iterator().next();
String name = entry.getKey();
String value = entry.getValue().getAsString();
return new HpackHeaderField(name, value);
}
@Override
public Double deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
try {
if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定义为double类型,如果后台返回""或者null,则返回0.00
return 0.0;
}
} catch (Exception ignore) {
}
try {
return json.getAsDouble();
} catch (NumberFormatException e) {
throw new JsonSyntaxException(e);
}
}
@Override
public Integer deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
try {
//定义为int类型,如果后台返回""或者null,则返回0
if (json.getAsString().equals("") || json.getAsString().equals("null")) {
return 0;
}
} catch (Exception ignore) {
}
try {
return json.getAsInt();
} catch (NumberFormatException e) {
throw new JsonSyntaxException(e);
}
}
@Override
public Device.DeviceOrientation deserialize(
JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
return json == null
? null
: Device.DeviceOrientation.valueOf(json.getAsString().toUpperCase(Locale.ROOT));
} catch (Exception e) {
logger.log(SentryLevel.ERROR, "Error when deserializing DeviceOrientation", e);
}
return null;
}
@Override
public SentryId deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
return json == null ? null : new SentryId(json.getAsString());
} catch (Exception e) {
logger.log(SentryLevel.ERROR, "Error when deserializing SentryId", e);
}
return null;
}
@Override
public TimeZone deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
return json == null ? null : TimeZone.getTimeZone(json.getAsString());
} catch (Exception e) {
logger.log(SentryLevel.ERROR, "Error when deserializing TimeZone", e);
}
return null;
}
@Override
public SentryLevel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
return json == null ? null : SentryLevel.valueOf(json.getAsString().toUpperCase(Locale.ROOT));
} catch (Exception e) {
logger.log(SentryLevel.ERROR, "Error when deserializing SentryLevel", e);
}
return null;
}
private @Nullable <T> T parseObject(
final @NotNull JsonDeserializationContext context,
final @NotNull JsonObject jsonObject,
final @NotNull String key,
final @NotNull Class<T> clazz)
throws JsonParseException {
final JsonObject object = jsonObject.getAsJsonObject(key);
if (object != null && !object.isJsonNull()) {
return context.deserialize(object, clazz);
}
return null;
}
@Override
public IdentityKey deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (null == json) {
return null;
}
try {
String jsonString = json.getAsString();
return new IdentityKey(Base64.decodeWithoutPadding(jsonString), 0);
} catch (Throwable e) {
throw new JsonParseException(e);
}
}
@Override
public ECPublicKey deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (null != json) {
try {
String publicSting = json.getAsString();
return Curve.decodePoint(Base64.decodeWithoutPadding(publicSting), 0);
} catch (Throwable e) {
throw new JsonParseException("unknown public key", e);
}
}
return null;
}
@Override
public sha256_object deserialize(JsonElement json,
Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
sha256_object sha256ObjectObject = new sha256_object();
BaseEncoding encoding = BaseEncoding.base16().lowerCase();
byte[] byteContent = encoding.decode(json.getAsString());
if (byteContent.length != 32) {
throw new JsonParseException("sha256_object size not correct.");
}
System.arraycopy(byteContent, 0, sha256ObjectObject.hash, 0, sha256ObjectObject.hash.length);
sha256ObjectObject.hash = byteContent;
return sha256ObjectObject;
}
@Override
public vote_id_type deserialize(JsonElement json,
Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
String strSerial = json.getAsString();
return new vote_id_type(strSerial);
}
@Override
public public_key_type deserialize(JsonElement json,
Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
String strPublicKey = json.getAsString();
try {
return new public_key_type(strPublicKey);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new JsonParseException("pubic key is invalid.");
}
}
@Override
public UnsignedLong deserialize(JsonElement json,
Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
UnsignedLong uLongObject = UnsignedLong.valueOf(json.getAsString());
return uLongObject;
}