1

我似乎无法从 Json 响应中找出嵌套对象。这是我的代码:

    import com.fasterxml.jackson.annotation.JsonCreator;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;
    import com.sun.xml.internal.org.jvnet.fastinfoset.stax.LowLevelFastInfosetStreamWriter;
    import io.sphere.sdk.categories.Category;
    import io.sphere.sdk.client.HttpRequestIntent;
    import io.sphere.sdk.client.JsonNodeSphereRequest;
    import io.sphere.sdk.client.SphereRequest;
    import io.sphere.sdk.http.HttpMethod;
    import io.sphere.sdk.http.HttpResponse;
    import io.sphere.sdk.json.SphereJsonUtils;
    import io.sphere.sdk.models.Base;
    import io.sphere.sdk.models.LocalizedString;
    import com.google.gson.Gson;

    import javax.annotation.Nullable;
    import java.lang.reflect.Type;
    import java.time.LocalDateTime;
    import java.util.*;


    public class EvaProduct {

        private String id;
        private LocalDateTime createdAt;
        private LocalDateTime lastModifiedAt;
        private LocalizedString name;
    //    private LocalizedString description;
    //    private Set<Category> categories;
    //    private Set<EvaVariant> veloVariants = new HashSet<>();


        @JsonCreator
        EvaProduct(@JsonProperty("id")  String id,
                   @JsonProperty("crdAt") LocalDateTime createdAt,
                   @JsonProperty("lastModifiedAt") LocalDateTime lastModifiedAt,
                   @JsonProperty("name") LocalizedString name ){

            this.id = id;
            this.createdAt = createdAt;
            this.lastModifiedAt = lastModifiedAt;
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public LocalDateTime getCreatedAt() { return createdAt; }

        public LocalDateTime getLastModifiedAt() {
            return lastModifiedAt;
        }

        public LocalizedString getName(){
            return name;
        }


        static SphereRequest<List<EvaProduct>> getAllEvaProducts(){
            return new GetAllEvaProducts();
        }


        @Override
        public String toString() {
            return "EvaProduct {" +
                    "id='" + id + '\'' +
                    ", createdAt=" + createdAt +
                    ", lastModifiedAt=" + lastModifiedAt +
                    ", name=" + name +
                    '}';
        }

        private static class GetAllEvaProducts extends Base implements SphereRequest<List<EvaProduct>> {

            public static final int MAX = 2;


            @Nullable
            @Override
            public List<EvaProduct> deserialize(HttpResponse httpResponse) {

                final JsonNode rootJsonNode = SphereJsonUtils.parse(httpResponse.getResponseBody());

                final JsonNode results = rootJsonNode.get("data").get("products").get("results");

                List<EvaProduct> evaProducts = SphereJsonUtils.readObject(results, new TypeReference<List<EvaProduct>>() { });

                return evaProducts;
            }

            @Override
            public HttpRequestIntent httpRequestIntent() {
                final String queryString = String.format("query product {\n" +
                        "       products(limit: %d) {\n" +
                        "           results {\n" +
                        "               id\n" +
                        "               createdAt\n" +
                        "               lastModifiedAt\n" +
                        "               masterData{\n" +
                        "                   current{\n" +
                        "                   name(locale: \"en\")" +
                        "                   }\n" +
                        "               }\n" +
                        "           }\n" +
                        "       }\n" +
                        "   }", MAX);
                final String body =String.format(
                        "{\n" +
                                "   \"query\": \"%s\"" +
                                "}", queryString.replace("\n", "\\n").replace("\"", "\\\""));
                return HttpRequestIntent.of(HttpMethod.POST, "/graphql", body);
            }
        }

    }

从控制器:

    import io.sphere.sdk.client.SphereClient;
    import io.sphere.sdk.client.SphereRequest;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.CompletionStage;
    import java.util.concurrent.ExecutionException;

    import static handson.impl.ClientService.createSphereClient;
    import static handson.EvaVariant.requestOfSkusEvaProducts;
    import static handson.EvaProduct.getAllEvaProducts;


    public class ZEvaKnowsGraphQL {
        private static final Logger LOG = LoggerFactory.getLogger(ZEvaKnowsGraphQL.class);

        public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
            try (final SphereClient client = createSphereClient()) {

                SphereRequest<List<EvaProduct>> allEvaProducts = getAllEvaProducts();

                CompletionStage<List<EvaProduct>> listCompletionStage = client.execute((allEvaProducts));

                List<EvaProduct> evaProducts1 = listCompletionStage.toCompletableFuture().get();

                for(EvaProduct evaProduct: evaProducts1) {
                    System.out.println(evaProduct.toString());
                }
            }
        }
    }

我设法从 GraphQL 请求中获得了完整的结果,因此 JsonNode 结果具有所有正确的值。例如,它看起来像这样:

[{"id":"098834e3-e636-4186-91e5-30176ee3c261","createdAt":"2019-12-18T14:38:53.617Z","lastModifiedAt":"2019-12-18T14:38:53.617Z","masterData":{"current":{"name":"cookie-BlueWine"}}},{"id":"238135fb-3fa0-4f54-9e52-d70e5bd38b43","createdAt":"2019-12-18T14:38:53.631Z","lastModifiedAt":"2019-12-21T19:22:33.324Z","masterData":{"current":{"name":"cookie-RedWinerru"}}}]

但是,我似乎无法将嵌套名称值放入我的 Java 对象中。所以 evaProducts 现在看起来像这样:

EvaProduct {id='098834e3-e636-4186-91e5-30176ee3c261', createdAt=2019-12-18T14:38:53.617, lastModifiedAt=2019-12-18T14:38:53.617, name=null} EvaProduct {id='238135fb-3fa0-4f54-9e52-d70e5bd38b43', createdAt=2019-12-18T14:38:53.631, lastModifiedAt=2019-12-21T19:22:33.324, name=null}

所以名称为空。有人可以给我一个关于如何解决这个问题的提示吗?如何将嵌套值放入正确的字段中?

4

2 回答 2

0

在您的 graphQL 查询中,您查询英语翻译,name(locale: \"en\")"因此结果将直接是英语的字符串,并且不能被解析为LocalizedString每个语言环境的一种字符串映射。

要解决此问题,您需要在EvaProduct类中将name字段更改为字符串,或者只需更新您的查询以获取所有语言环境的对象。

于 2019-12-24T10:10:32.450 回答
0

好吧,所以我在某个地方找到了答案。是的@Schleichardt,LocalizedString 也需要更改为字符串,谢谢你,而且:我需要添加一个字段:private final Map masterData; 它将从响应中获取主数据,然后我可以在 jsonCreator/constructor 中使用它来提取名称的值,如下所示: this.name = ((String)((Map)masterdata.get("current")) .get("名称")); 瞧,它有效!

于 2019-12-27T10:44:30.550 回答