我希望能够在Java操作方法中访问JSON字符串中的属性。这个字符串可以通过myJsonString = object.getJson()得到。下面是字符串看起来的一个例子:
{
'title': 'ComputingandInformationsystems',
'id': 1,
'children': 'true',
'groups': [{
'title': 'LeveloneCIS',
'id': 2,
'children': 'true',
'groups': [{
'title': 'IntroToComputingandInternet',
'id': 3,
'children': 'false',
'groups': []
}]
}]
}
在这个字符串中,每个JSON对象都包含一个其他JSON对象的数组。其目的是提取一个id列表,其中任何给定对象拥有包含其他JSON对象的group属性。我认为谷歌的Gson是一个潜在的JSON插件。谁能提供一些形式的指导,我如何从这个JSON字符串生成Java ?
试试boon吧:
https://github.com/RichardHightower/boon
它快得出奇。
https://github.com/RichardHightower/json-parsers-benchmark
不要相信我的话……查看加特林基准。
https://github.com/gatling/json-parsers-benchmark
(在某些情况下高达4x,并且在测试的100个测试中。它还有一个索引覆盖模式,甚至更快。它很年轻,但已经有了一些用户。)
它可以解析JSON到地图和列表比任何其他库可以解析到JSON DOM更快,这是没有索引覆盖模式。与Boon索引叠加模式,它甚至更快。
它还具有非常快速的JSON lax模式和PLIST解析器模式。:)(并且具有非常低的内存,直接从UTF-8编码的bytes模式运行)。
它还具有最快的JSON到JavaBean模式。
它是新的,但如果速度和简单的API是你所追求的,我认为没有更快或更简单的API了。
<!-- GSON -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.7</version>
</dependency>
@Test
void readListJsonFromFileTest() throws IOException {
Type type = new TypeToken<List<SimplePojo>>(){}.getType();
String fromJsonFile = readFromJsonFile("json/simplePojoJsonList.json");
List<SimplePojo> pojoList = gson.fromJson(fromJsonFile, type);
Assertions.assertNotNull(pojoList);
}
@Test
void readJsonFromFileTest() throws IOException {
Type type = new TypeToken<SimplePojo>(){}.getType();
String fromJsonFile = readFromJsonFile("json/simplePojoJson.json");
SimplePojo simplePojo = gson.fromJson(fromJsonFile, type);
Assertions.assertNotNull(simplePojo);
}
String readFromJsonFile(String pathToJson) throws IOException {
InputStream resource = new ClassPathResource(pathToJson).getInputStream();
String json = StreamUtils.copyToString(resource, StandardCharsets.UTF_8);
return json;
}
最简单的方法是使用softconvertvalue方法,这是一个自定义方法,可以将jsonData转换为特定的Dto类。
Dto response = softConvertValue(jsonData, Dto.class);
public static <T> T softConvertValue(Object fromValue, Class<T> toValueType)
{
ObjectMapper objMapper = new ObjectMapper();
return objMapper
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.convertValue(fromValue, toValueType);
}