将Json反序列化为Java对象

时间:2019-04-06 17:35:27

标签: java json lombok

我正在使用Lombok为我的java对象创建构建器模式,我想将json转换为该对象,但一直说不能反序列化对象。

@Builder
@Getter
@Setter
@Value
@NoArgConstructor
@JsonDeserialize()
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class SaleInfo {
      private String country;
      private String saleability; //This
      private boolean isEbook; //THis
     // created only if required
      private String buyLink;

    //TODO i want to have a conditional creation of this two objects below.
      ListPrice listPrice;
      RetailPrice retailPrice;

    @Override
    public boolean equals(Object o) {
        return EqualsBuilder.reflectionEquals(this, o);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }

这是我使用对象映射器的代码

public NodeBean readFromJsonFile() throws IOException {
    objectMapper.configure(
        DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("book.json");
        JsonNode node = objectMapper.readTree(resourceAsStream);
        NodeBean nodebean = objectMapper.readerFor(NodeBean.class).readValue(node);
    return nodebean;
}

当我实现getter和setter并删除所有lombok批注时,它可以很好地工作,但是我需要它作为构建器模式,这很重要(由于某些可选对象,例如Listprice)。

我尝试反序列化时出现错误

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.valentine.cognifide_task.model.SaleInfo` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.valentine.cognifide_task.model.NodeBean["items"]->java.util.ArrayList[0]->com.valentine.cognifide_task.model.Item["saleInfo"])

这是json,json的其他部分我有对象,它们还可以,只有saleInfo出现问题,因为该字段正在更改,有时它具有Listprice,而有时没有,所以我想要一个只能创建的生成器类如果需要的话。

 {
      "kind": "books#volume",
      "id": "UEdjAgAAQBAJ",
      "etag": "/KAuiIWJuB4",
      "selfLink": "https://www.googleapis.com/books/v1/volumes/UEdjAgAAQBAJ",
      "volumeInfo": {
        "title": "Java. Podstawy. Wydanie IX",
        "authors": [
          "Cay S. Horstmann",
          "Gary Cornell"
        ],
        "publisher": "Helion",
        "publishedDate": "2013-12-09",
        "description": "Kolejne wydanie tej cenionej książki zostało zaktualizowane o wszystkie nowości, które pojawiły się w wersji 7 platformy Java Standard Edition. W trakcie lektury poznasz składnię języka oraz wszystkie istotne kwestie związane z programowaniem w Javie. Zrozumiesz założenia programowania obiektowego, nauczysz się korzystać z interfejsów oraz obsługiwać wyjątki. Przekonasz się również, jakie ułatwienia w tym zakresie oferuje Java 7 obsługa wielu wyjątków w ramach jednego bloku catch to tylko czubek góry lodowej.",
        "industryIdentifiers": [
          {
            "type": "ISBN_13",
            "identifier": "9788324677610"
          },
          {
            "type": "ISBN_10",
            "identifier": "8324677615"
          }
        ],
        "readingModes": {
          "text": true,
          "image": true
        },
        "pageCount": 864,
        "printType": "BOOK",
        "categories": [
          "Computers"
        ],
        "maturityRating": "NOT_MATURE",
        "allowAnonLogging": true,
        "contentVersion": "2.5.4.0.preview.3",
        "imageLinks": {
          "smallThumbnail": "http://books.google.com/books/content?id=UEdjAgAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
          "thumbnail": "http://books.google.com/books/content?id=UEdjAgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
        },
        "language": "pl",
        "previewLink": "http://books.google.pl/books?id=UEdjAgAAQBAJ&pg=PA852&dq=java&hl=&cd=4&source=gbs_api",
        "infoLink": "https://play.google.com/store/books/details?id=UEdjAgAAQBAJ&source=gbs_api",
        "canonicalVolumeLink": "https://market.android.com/details?id=book-UEdjAgAAQBAJ"
      },
      "saleInfo": {
        "country": "PL",
        "saleability": "FOR_SALE",
        "isEbook": true,
        "listPrice": {
          "amount": 79.0,
          "currencyCode": "PLN"
        },
        "retailPrice": {
          "amount": 55.3,
          "currencyCode": "PLN"
        },
        "buyLink": "https://play.google.com/store/books/details?id=UEdjAgAAQBAJ&rdid=book-UEdjAgAAQBAJ&rdot=1&source=gbs_api",
        "offers": [
          {
            "finskyOfferType": 1,
            "listPrice": {
              "amountInMicros": 7.9E7,
              "currencyCode": "PLN"
            },
            "retailPrice": {
              "amountInMicros": 5.53E7,
              "currencyCode": "PLN"
            }
          }
        ]
      },
      "accessInfo": {
        "country": "PL",
        "viewability": "PARTIAL",
        "embeddable": true,
        "publicDomain": false,
        "textToSpeechPermission": "ALLOWED",
        "epub": {
          "isAvailable": true,
          "acsTokenLink": "http://books.google.pl/books/download/Java_Podstawy_Wydanie_IX-sample-epub.acsm?id=UEdjAgAAQBAJ&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
        },
        "pdf": {
          "isAvailable": true,
          "acsTokenLink": "http://books.google.pl/books/download/Java_Podstawy_Wydanie_IX-sample-pdf.acsm?id=UEdjAgAAQBAJ&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
        },
        "webReaderLink": "http://play.google.com/books/reader?id=UEdjAgAAQBAJ&hl=&printsec=frontcover&source=gbs_api",
        "accessViewStatus": "SAMPLE",
        "quoteSharingAllowed": false
      },
      "searchInfo": {
        "textSnippet": "MF, 512 manifestu klasa główna, 514 sekcja główna, 512 wstawianie sekcji, 518 \u003cbr\u003e\nzmienianie zawartości, 513 MapTest.\u003cb\u003ejava\u003c/b\u003e,699 MenuFrame.\u003cb\u003ejava\u003c/b\u003e, 442 \u003cbr\u003e\nMethodTableTest.\u003cb\u003ejava\u003c/b\u003e,266 MouseComponent.\u003cb\u003ejava\u003c/b\u003e, 383 MouseFrame.\u003cb\u003ejava\u003c/b\u003e, 383 \u003cbr\u003e\nNotHelloWorld.\u003cb\u003ejava\u003c/b\u003e, 330, 534 ObjectAnalyzerTest.\u003cb\u003ejava\u003c/b\u003e,259 OptionDialogFrame.\u003cbr\u003e\n\u003cb\u003ejava\u003c/b\u003e,477 overview.html, 194 PackageTest.\u003cb\u003ejava\u003c/b\u003e, 184 PairTest1.\u003cb\u003ejava\u003c/b\u003e, 631 \u003cbr\u003e\nPairTest2.\u003cb\u003ejava\u003c/b\u003e, 634 PairTest3.\u003cb\u003ejava\u003c/b\u003e, 656 ParamTest.\u003cb\u003ejava\u003c/b\u003e, 169 PasswordChooser.\u003cbr\u003e\n\u003cb\u003ejava\u003c/b\u003e, 492 Person.\u003cb\u003ejava\u003c/b\u003e ..."
      }
    },

1 个答案:

答案 0 :(得分:2)

似乎您缺少带有@JsonCreator标签和@JsonProperty标签的构造函数。

我现在正在一个项目中,在jax-rs上下文中使用它。

Looking into it,似乎杰克逊实际上可能并未使用必需的属性。

@Builder
@Getter
@Setter
@Value
@RequiredArgsConstructor
@JsonDeserialize()
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class SaleInfo {
      private String country;
      private String saleability; //This
      private boolean isEbook; //THis
     // created only if required
      private String buyLink;

    //TODO i want to have a conditional creation of this two objects below.
      ListPrice listPrice;
      RetailPrice retailPrice;

    @JsonCreator
    public SaleInfo(
        @JsonProperty("country") String country;
        @JsonProperty("saleability") String saleability;
        @JsonProperty("isEbook") boolean isEbook;
        @JsonProperty(value = "buyLink", required = false) String buyLink;
        @JsonProperty(value = "listPrice", required = false) ListPrice listPrice;
        @JsonProperty(value = "retailPrice", required = false) RetailPrice retailPrice;
    ) {
     this.country = country;
     this.saleability = saleability;
     this.isEbook = isEbook;
     this.buyLink = buyLink;
     this.listPrice = listPrice;
     this.retailPrice = country;

    }


    @Override
    public boolean equals(Object o) {
        return EqualsBuilder.reflectionEquals(this, o);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }