我有JSON paylaod如下:

{
  "status": "ok",
  "result": {
    "result": [
      {
        "product_id": "1420-131617-82",
        "sku": "1420-131617",
        "display_sku": "8DD 355 100-411",
        "genart_number": 82,
        "name": "Bremsscheibe",
        "description": null,
        "additional_info_text": null,
        "product_url": "https://www.autoteile5000.de/product/1420-131617-82",
        "image_url": "https://static.autoteile5000.de/product-images/HLP/4625-462502682-3-255-1548045462267.jpg",
        "brand": "HELLA PAGID",
        "eans": [
          "4082300365078"
        ],
        "manufacturer_product_number": "8DD 355 100-411",
        "data_supplier_number": "4625",
        "pricehammer": false,
        "buyable": true,
        "bulky_good": false,
        "risky_good": false,
        "hazardous_good": false,
        "car_specific": true,
        "has_deposit": false,
        "is_exchange_part": false,
        "visibility_status": "active",
        "deleted": false
      }
    ]
  }
}


这是我反序列化的方法:

public List<SimpleProductDto> getProducts(ProductForm productForm) {

    JsonParser jsonParser = new JsonParser();
    try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("data/product/2210-0929-818/product.json") ) {
        String text = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
        //System.out.println("print text : " + text);
        //Read JSON file
        JsonObject objectFromString = jsonParser.parse(text).getAsJsonObject();
       // System.out.println(objectFromString.toString());

        JsonObject objectFromString1 = objectFromString.getAsJsonObject("result");
       // System.out.println(objectFromString.toString());

       // System.out.println(objectFromString1.toString());

        JsonArray jsonArray = objectFromString1.getAsJsonArray("result");
        System.out.println("printing json array : " +jsonArray.toString());

        ObjectMapper oMapper = new ObjectMapper();
        for(JsonElement element : jsonArray){
            JsonObject productObj = element.getAsJsonObject();
            System.out.println("printing json object : " + productObj.toString());
            SimpleproductDtoMapper productDtoList = oMapper.readValue(productObj.toString(), SimpleproductDtoMapper.class);
        }
      // List<SimpleproductDtoMapper> productDtoList = oMapper.readValue(jsonArray.toString(), new TypeReference<List<SimpleproductDtoMapper>>() {});

       // Map<String, SimpleproductDtoMapper> items = productDtoList.stream().collect(Collectors.toMap(SimpleproductDtoMapper::getProductId, Function.identity()));

        //items.forEach((k, v) -> System.out.println("Item : " + k + " Count : " + v));

        //Iterate over employee array
        //productList.forEach(emp -> parseProductObject((JSONObject) emp));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


这是我的POJO

public class SimpleproductDtoMapper {

@SerializedName("product_id")
private String productId;
private String sku;
@SerializedName("display_sku")
private String displaySku;
@SerializedName("genart_number")
private Integer genartNumber;
private String name;
private String description;
@SerializedName("additional_info_text")
private String additionalInfoText;
@SerializedName("product_url")
private String productUrl;
@SerializedName("image_url")
private String imageUrl;
private String brand;
private List<String> eans;
@SerializedName("manufacturer_product_number")
private String manufacturerProductNumber;
@SerializedName("data_supplier_number")
private String dataSupplierNumber;
private boolean pricehammer;
private boolean buyable;
@SerializedName("bulky_good")
private boolean bulkyGood;
@SerializedName("risky_good")
private boolean riskyGood;
@SerializedName("hazardous_good")
private boolean hazardousGood;
@SerializedName("car_specific")
private boolean carSpecific;
@SerializedName("has_deposit")
private boolean hasDeposit;
@SerializedName("is_exchange_part")
private boolean isExchangePart;
@SerializedName("visibility_status")
private VisibilityStatusDto visibilityStatus;
@SerializedName("deleted")
private boolean deleted;
}


我得到以下异常:


  在[来源:
  (字符串)“ {” product_id“:” 1420-131617-82“,” sku“:” 1420-131617“,” display_sku“:” 8DD
  355
  100-411“,” genart_number“:82,”名称“:” Bremsscheibe“,”描述“:null,” additional_info_text“:null,” product_url“:” https://www.autoteile5000.de/product/1420-131617-82“,” image_url“:” https://static.autoteile5000.de/product-images/HLP/4625-462502682-3-255-1548045462267.jpg“ ,“品牌”:“ HELLA
  PAGID“,” eans“:[” 4082300365078“],” manufacturer_product_number“:” 8DD 355
  100-411“,” data_supplier_number“:” 4625“,” pricehammer“:false,” buyable“:tr” [被截断
  174个字符];行:1,列:16](通过参考链:
  com.kfz24.mockingservice.mapper.SimpleproductDtoMapper [“ product_id”])
    在
  com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)
    在
  com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:823)
    在
  com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1153)
    在
  com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1589)
    在
  com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1567)
    在
  com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)
    在
  com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    在
  com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    在com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    在com.kfz24.mockingservice.service.impl.MockingProductServiceImpl.getProducts(MockingProductServiceImpl.java:49)
    在com.kfz24.mockingservice.controller.MockingProductController.getProducts(MockingProductController.java:29)

最佳答案

使用jsonschema2pojo可以生成带有POJO批注的Jackson类。选择Jackson 2.x以生成带有Jackson批注的模型。 Source type应该是JSON。在下面,您可以看到我使用此工具生成的Product类。所有属性均为public,因此将其更改为private并生成getterssetters

class Product {

    @JsonProperty("product_id")
    public String productId;
    @JsonProperty("sku")
    public String sku;
    @JsonProperty("display_sku")
    public String displaySku;
    @JsonProperty("genart_number")
    public Integer genartNumber;
    @JsonProperty("name")
    public String name;
    @JsonProperty("description")
    public Object description;
    @JsonProperty("additional_info_text")
    public Object additionalInfoText;
    @JsonProperty("product_url")
    public String productUrl;
    @JsonProperty("image_url")
    public String imageUrl;
    @JsonProperty("brand")
    public String brand;
    @JsonProperty("eans")
    public List<String> eans = null;
    @JsonProperty("manufacturer_product_number")
    public String manufacturerProductNumber;
    @JsonProperty("data_supplier_number")
    public String dataSupplierNumber;
    @JsonProperty("pricehammer")
    public Boolean pricehammer;
    @JsonProperty("buyable")
    public Boolean buyable;
    @JsonProperty("bulky_good")
    public Boolean bulkyGood;
    @JsonProperty("risky_good")
    public Boolean riskyGood;
    @JsonProperty("hazardous_good")
    public Boolean hazardousGood;
    @JsonProperty("car_specific")
    public Boolean carSpecific;
    @JsonProperty("has_deposit")
    public Boolean hasDeposit;
    @JsonProperty("is_exchange_part")
    public Boolean isExchangePart;
    @JsonProperty("visibility_status")
    public String visibilityStatus;
    @JsonProperty("deleted")
    public Boolean deleted;

    @Override
    public String toString() {
        return "Product{" +
                "productId='" + productId + '\'' +
                ", sku='" + sku + '\'' +
                ", displaySku='" + displaySku + '\'' +
                ", genartNumber=" + genartNumber +
                ", name='" + name + '\'' +
                ", description=" + description +
                ", additionalInfoText=" + additionalInfoText +
                ", productUrl='" + productUrl + '\'' +
                ", imageUrl='" + imageUrl + '\'' +
                ", brand='" + brand + '\'' +
                ", eans=" + eans +
                ", manufacturerProductNumber='" + manufacturerProductNumber + '\'' +
                ", dataSupplierNumber='" + dataSupplierNumber + '\'' +
                ", pricehammer=" + pricehammer +
                ", buyable=" + buyable +
                ", bulkyGood=" + bulkyGood +
                ", riskyGood=" + riskyGood +
                ", hazardousGood=" + hazardousGood +
                ", carSpecific=" + carSpecific +
                ", hasDeposit=" + hasDeposit +
                ", isExchangePart=" + isExchangePart +
                ", visibilityStatus='" + visibilityStatus + '\'' +
                ", deleted=" + deleted +
                '}';
    }
}


我注意到您想跳过result(Object) -> result(Array)级别。了解如何使用Jackson来做到这一点:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.CollectionType;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        JsonNode jsonNode = mapper
                .reader()
                .at("/result/result")
                .readTree(new FileInputStream(jsonFile));

        CollectionType productsType = mapper.getTypeFactory().constructCollectionType(List.class, Product.class);
        List<Product> products = mapper.convertValue(jsonNode, productsType);
        System.out.println(products);
    }
}


上面的代码打印:

[Product{productId='1420-131617-82', sku='1420-131617', displaySku='8DD 355 100-411', genartNumber=82, name='Bremsscheibe', description=null, additionalInfoText=null, productUrl='https://www.autoteile5000.de/product/1420-131617-82', imageUrl='https://static.autoteile5000.de/product-images/HLP/4625-462502682-3-255-1548045462267.jpg', brand='HELLA PAGID', eans=[4082300365078], manufacturerProductNumber='8DD 355 100-411', dataSupplierNumber='4625', pricehammer=false, buyable=true, bulkyGood=false, riskyGood=false, hazardousGood=false, carSpecific=true, hasDeposit=false, isExchangePart=false, visibilityStatus='active', deleted=false}]

关于java - Jackson库中的UnrecognizedPropertyException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54890696/

10-14 12:32