Jayway JsonPath 是一个 Java 库,用于从 JSON 文档中提取数据,类似于 XPath 对 XML 的操作。它提供了一种简洁的方式来查询和操作 JSON 数据。
当使用 Jayway JsonPath 读取 JSON 中的长整型数值时,可能会遇到以下问题:
Configuration conf = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.options(Option.SUPPRESS_EXCEPTIONS)
.build();
Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonString);
Long value = JsonPath.using(conf).parse(document).read("$.longValue", Long.class);
String json = "{\"id\": 1234567890123456789}";
DocumentContext ctx = JsonPath.parse(json);
long id = ctx.read("$.id", Long.class);
String json = "{\"bigNumber\": 1234567890123456789}";
BigDecimal bigDecimal = JsonPath.read(json, "$.bigNumber", BigDecimal.class);
long longValue = bigDecimal.longValue();
public class CustomJsonProvider extends AbstractJsonProvider {
@Override
public Object createArray() {
return new ArrayList<>();
}
@Override
public Object createMap() {
return new LinkedHashMap<>();
}
@Override
public Object parse(String json) throws ParseException {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(json, Object.class);
} catch (IOException e) {
throw new ParseException(e);
}
}
@Override
public Object getArrayIndex(Object obj, int idx) {
return ((List<?>) obj).get(idx);
}
@Override
public Object getMapValue(Object obj, String key) {
return ((Map<?, ?>) obj).get(key);
}
@Override
public boolean isArray(Object obj) {
return obj instanceof List;
}
@Override
public boolean isMap(Object obj) {
return obj instanceof Map;
}
}
// 使用自定义 Provider
Configuration conf = Configuration.builder()
.jsonProvider(new CustomJsonProvider())
.build();
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
public class JsonPathLongExample {
public static void main(String[] args) {
String json = "{\"timestamp\": 1640995200000, \"userId\": 1234567890123456789}";
// 方法1:直接读取为Long
Long timestamp = JsonPath.read(json, "$.timestamp", Long.class);
System.out.println("Timestamp: " + timestamp);
// 方法2:使用DocumentContext
DocumentContext ctx = JsonPath.parse(json);
Long userId = ctx.read("$.userId", Long.class);
System.out.println("User ID: " + userId);
// 方法3:使用自定义配置
Configuration conf = Configuration.defaultConfiguration()
.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
Long safeRead = JsonPath.using(conf).parse(json).read("$.timestamp", Long.class);
System.out.println("Safe read: " + safeRead);
}
}
通过以上方法,可以确保在使用 Jayway JsonPath 时正确处理长整型数值,避免精度丢失和类型转换问题。