You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.9 KiB

package common.ecommerce.http;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.util.ArrayList;
import java.util.List;
/**
* Jackson 实现。
*/
public final class JacksonJsonCodec implements JsonCodec {
private final ObjectMapper mapper;
public JacksonJsonCodec() {
this.mapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public ObjectMapper mapper() {
return mapper;
}
@Override
public String toJson(Object value) {
try {
return mapper.writeValueAsString(value);
} catch (Exception e) {
throw new IllegalArgumentException("serialize failed", e);
}
}
@Override
public <T> T fromJson(String json, Class<T> type) {
try {
return mapper.readValue(json, type);
} catch (Exception e) {
throw new IllegalArgumentException("deserialize failed for " + type.getSimpleName(), e);
}
}
@Override
public String stringAt(String json, String pointer) {
JsonNode node = nodeAt(json, pointer);
return node == null || node.isNull() ? null : node.asText();
}
/** 按点路径取节点,如 {@code data.list}。数组下标用数字段。 */
public JsonNode nodeAt(String json, String pointer) {
if (json == null || pointer == null || pointer.isEmpty()) {
return null;
}
try {
JsonNode cur = mapper.readTree(json);
for (String seg : pointer.split("\\.")) {
if (cur == null || cur.isNull()) {
return null;
}
if (cur.isArray() && seg.matches("\\d+")) {
cur = cur.get(Integer.parseInt(seg));
} else {
cur = cur.get(seg);
}
}
return cur;
} catch (Exception e) {
return null;
}
}
/** 按点路径取整数值;节点缺失、非数字或为 null 时返回哨兵 {@code missing}。 */
public int intAt(String json, String pointer, int missing) {
JsonNode node = nodeAt(json, pointer);
if (node == null || node.isNull() || !node.canConvertToInt()) {
return missing;
}
return node.asInt();
}
/** 把点路径下的数组节点反序列化为列表。 */
public <T> List<T> listAt(String json, String pointer, Class<T> type) {
JsonNode node = nodeAt(json, pointer);
if (node == null || !node.isArray()) {
return new ArrayList<T>();
}
List<T> out = new ArrayList<T>(node.size());
for (JsonNode item : (ArrayNode) node) {
out.add(mapper.convertValue(item, type));
}
return out;
}
}