我希望能够在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 ?


当前回答

或者杰克逊:

String json = "...";
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});

其他回答

如果您使用带有特殊映射的键或值的任何类型的特殊映射,您将发现谷歌的实现并没有考虑到这一点。

根据输入的JSON格式(字符串/文件)创建一个jSONString。JSON对应的Message类对象示例如下:

Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);

最简单的方法是使用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);
}

或者杰克逊:

String json = "...";
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});

        <!-- 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;
    }