元帅GraphQl执行结果对Java对象

发布于 2025-01-30 18:58:42 字数 1306 浏览 3 评论 0原文

我搜索了很多东西,但是不幸的是,任何建议的解决方案都适合我。

我将描述要点:

  1. 我的休息项目建立在OpenAPI和 OpenApi Maven Generator插件上。
  2. 通过JAXRS-Spec生成器I生成应用程序DTO。
  3. 通过graphQl-nodejs-express-server Generator,我生产GraphQl架构文件。
  4. REST Web服务作为可选的GraphQl查询接受,以过滤/减少答案的冗长。

GraphQl executionResult.getData()方法返回linkedHashmap的实例。

问题是:如何将上述linkedhashmap降低到相应的dto

预先感谢您!

------ 编辑 ----

我希望改进和简化我的问题。

我有以下DTO:

public class ResponseDTO {
    private Integer id;
    private String description;
}

我通过GraphQl过滤:

GraphQLSchema graphQLSchema = getGraphQLSchema();
String        graphqlQuery  = "{ ResponseDTO { id } }";

ExecutionInput builder = ExecutionInput
    .newExecutionInput()
    .query(graphqlQuery)
    .build();

ExecutionResult executionResult = GraphQL
    .newGraphQL(graphQLSchema)
    .build()
    .execute(builder);
    
LinkedHashMap graphQLData = executionResult.getData();

//TODO How can I convert 'graphQLData' to a `ResponseDTO` instance?

ResponseDTO responseDTO = ???;

I searched a lot into SO, but unfortunately any of the proposed solutions fits to me.

I am going to describe the key points:

  1. My REST project is built upon OpenAPI and the OpenAPI maven generator plugin.
  2. By the jaxrs-spec generator I produce the application DTOs.
  3. By the graphql-nodejs-express-server generator I produce the GraphQL schema files.
  4. The REST web service accepts, as optional, a GraphQL query in order to filter/reduce the verbosity of the answer.

The GraphQL ExecutionResult.getData() method returns an instance of a LinkedHashMap.

The question is: How can I marshall the above LinkedHashMap to the corresponding DTO?

Thank you so much in advance!

----
Edit
----

I wish to improve and simplify my question.

I have a DTO such the following one:

public class ResponseDTO {
    private Integer id;
    private String description;
}

I filter it by GraphQL:

GraphQLSchema graphQLSchema = getGraphQLSchema();
String        graphqlQuery  = "{ ResponseDTO { id } }";

ExecutionInput builder = ExecutionInput
    .newExecutionInput()
    .query(graphqlQuery)
    .build();

ExecutionResult executionResult = GraphQL
    .newGraphQL(graphQLSchema)
    .build()
    .execute(builder);
    
LinkedHashMap graphQLData = executionResult.getData();

//TODO How can I convert 'graphQLData' to a `ResponseDTO` instance?

ResponseDTO responseDTO = ???;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

她说她爱他 2025-02-06 18:58:42

我终于找到了解决方案:

LinkedHashMap<String, Object> dataMap      = executionResult.getData();
String                        dataKey      = dataMap.keySet().toArray()[0].toString();
HashMap<String, Object>       dataValue    = (HashMap<String, Object>)dataMap.get(dataKey);

fixTypeId(
    dataContext.getClass(),
    dataValue
);

ObjectMapper             objectMapper = new ObjectMapper();

objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.registerModule(new JavaTimeModule());
objectMapper.registerModule(new JaxbAnnotationModule());
objectMapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));           objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

String dataJSON = objectMapper.writeValueAsString(dataValue);

ResponseDTO responseDTO = objectMapper.readValue(
    dataJSON,
    ResponseDTO.class
);

其中fixTypeid是:

@SuppressWarnings("unchecked")
private void fixTypeId(Class<?> refClass, Map<String, Object> dataMap) {
    JsonTypeInfo typeInfoAnnotation = refClass.getDeclaredAnnotation(JsonTypeInfo.class);
    JsonTypeName typeNameAnnotation = refClass.getDeclaredAnnotation(JsonTypeName.class);

    if ((null != typeInfoAnnotation) && (null != typeNameAnnotation)) {
        String typeInfo = typeInfoAnnotation.property();
        String typeName = typeNameAnnotation.value();

        log.trace(
            "Adding \"{} = {}\" type identifier.",
            typeInfo,
            typeName
        );

        dataMap.put(typeInfo, typeName);
    }

    dataMap
        .entrySet()
        .stream()
        .filter(entry -> (entry.getValue() instanceof Map))
        .forEach(entry -> {
            Field field = null;

            try {
                field = refClass.getDeclaredField(entry.getKey());
            } catch (NoSuchFieldException exception) {
                log.error(exception.getMessage(), exception);
                throw new RuntimeException(exception);
            }

            fixTypeId(
                field.getType(),
                (Map<String, Object>)entry.getValue()
            );
        });
}

I finally found the solution:

LinkedHashMap<String, Object> dataMap      = executionResult.getData();
String                        dataKey      = dataMap.keySet().toArray()[0].toString();
HashMap<String, Object>       dataValue    = (HashMap<String, Object>)dataMap.get(dataKey);

fixTypeId(
    dataContext.getClass(),
    dataValue
);

ObjectMapper             objectMapper = new ObjectMapper();

objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.registerModule(new JavaTimeModule());
objectMapper.registerModule(new JaxbAnnotationModule());
objectMapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));           objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

String dataJSON = objectMapper.writeValueAsString(dataValue);

ResponseDTO responseDTO = objectMapper.readValue(
    dataJSON,
    ResponseDTO.class
);

Where fixTypeId is:

@SuppressWarnings("unchecked")
private void fixTypeId(Class<?> refClass, Map<String, Object> dataMap) {
    JsonTypeInfo typeInfoAnnotation = refClass.getDeclaredAnnotation(JsonTypeInfo.class);
    JsonTypeName typeNameAnnotation = refClass.getDeclaredAnnotation(JsonTypeName.class);

    if ((null != typeInfoAnnotation) && (null != typeNameAnnotation)) {
        String typeInfo = typeInfoAnnotation.property();
        String typeName = typeNameAnnotation.value();

        log.trace(
            "Adding \"{} = {}\" type identifier.",
            typeInfo,
            typeName
        );

        dataMap.put(typeInfo, typeName);
    }

    dataMap
        .entrySet()
        .stream()
        .filter(entry -> (entry.getValue() instanceof Map))
        .forEach(entry -> {
            Field field = null;

            try {
                field = refClass.getDeclaredField(entry.getKey());
            } catch (NoSuchFieldException exception) {
                log.error(exception.getMessage(), exception);
                throw new RuntimeException(exception);
            }

            fixTypeId(
                field.getType(),
                (Map<String, Object>)entry.getValue()
            );
        });
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文