How to get around error "Unrecognized field "Name, not marked as ignorable", to insert JSON data into H2 database with Spring?

huangapple go评论80阅读模式
英文:

How to get around error "Unrecognized field "Name, not marked as ignorable", to insert JSON data into H2 database with Spring?

问题

我正试图按照这个Dan Vega在YouTube上的视频中所示的步骤,将以下JSON数据插入到H2数据库中,并使用Spring。但是,我遇到了以下错误:

<strong>错误</strong>:
> 无法保存产品:无法识别的字段“Name”(类com.saurabhsomani.domain.Product),未标记为可忽略的字段(已知属性有:"salesCount", "price", "name", "category", "cust_rating", "id"])
在[源:(BufferedInputStream);行:2,列:12]处(通过引用链:java.util.ArrayList[0]->com.saurabhsomani.domain.Product["Name"])

你能帮我解决这个问题吗?以下是代码细节:

我的<strong>JSON</strong>(product.json)如下所示:

[{
    "Name": "P1",
    "ID": 1,
    "Price": 970,
    "SalesCount": 300,
    "Category": "A",
    "Cust_Rating": 3.7
},
{
    "Name": "P2",
    "ID": 2,
    "Price": 1170,
    "SalesCount": 718,
    "Category": "A",
    "Cust_Rating": 3.8
},
{
    "Name": "P3",
    "ID": 3,
    "Price": 1090,
    "SalesCount": 1253,
    "Category": "A",
    "Cust_Rating": 0.5
}
]

项目结构如下:
项目结构

<strong>JsondbApplication.java</strong>

package com.saurabhsomani;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.saurabhsomani.domain.Product;
import com.saurabhsomani.service.ProductService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@SpringBootApplication
public class JsondbApplication {

    public static void main(String[] args) {

        SpringApplication.run(JsondbApplication.class, args);
    }

    @Bean
    CommandLineRunner runner(ProductService productService){ 
        return args -&gt; { 
            ObjectMapper mapper = new ObjectMapper();
            TypeReference&lt;List&lt;Product&gt;&gt; typeReference = new TypeReference&lt;List&lt;Product&gt;&gt;(){};
            InputStream inputStream = TypeReference.class.getResourceAsStream("/json/product.json");
            try{
                List&lt;Product&gt; products = mapper.readValue(inputStream, typeReference);
                productService.save(products);
                System.out.println("Products Saved!");
            } catch (IOException e){
                System.out.println("Unable to save products: " + e.getMessage());
            }
        };
    }
}

<strong>ProductController.java</strong>

package com.saurabhsomani.controller;

import com.saurabhsomani.domain.Product;
import com.saurabhsomani.service.ProductService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/products")
public class ProductController {

    private ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    public ProductService getProductService() {
        return productService;
    }

    @GetMapping("/list")
    public Iterable<Product> list(){
        return productService.list();
    }
}

<strong>Product.java</strong>

package com.saurabhsomani.domain;

import lombok.AllArgsConstructor;
import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Data
@AllArgsConstructor
@Entity
public class Product {

    @Id
    @GeneratedValue( strategy = GenerationType.AUTO)
    private String name;
    private int id;
    private int price;
    private int salesCount;
    private String category;
    private double cust_rating;

    public Product(){

    }
}

<strong>ProductService.java</strong>

package com.saurabhsomani.service;

import com.saurabhsomani.domain.Product;
import com.saurabhsomani.repository.ProductRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductService {

    private ProductRepository productRepository;

    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public Iterable<Product> list(){
        return productRepository.findAll();
    }

    public Product save(Product product){
        return productRepository.save(product);
    }

    public void save(List<Product> products) {
        productRepository.saveAll(products);
    }
}

<strong>ProductRepository</strong>

package com.saurabhsomani.repository;

import com.saurabhsomani.domain.Product;
import org.springframework.data.repository.CrudRepository;

public interface ProductRepository extends CrudRepository<Product, String>{

}
英文:

I am trying to insert the following json data into H2 database with Spring by following the process shown in this Dan Vega video on YouTube. But, I get the following error:

<strong>Error</strong>:
>Unable to save products: Unrecognized field "Name" (class com.saurabhsomani.domain.Product), not marked as ignorable (6 known properties: "salesCount", "price", "name", "category", "cust_rating", "id"])
at [Source: (BufferedInputStream); line: 2, column: 12] (through reference chain: java.util.ArrayList[0]->com.saurabhsomani.domain.Product["Name"])

Could you please help me fix this issue? Below are the code details:

My <strong>JSON</strong> (product.json) looks like:

[{
		&quot;Name&quot;: &quot;P1&quot;,
		&quot;ID&quot;: 1,
		&quot;Price&quot;: 970,
		&quot;SalesCount&quot;: 300,
		&quot;Category&quot;: &quot;A&quot;,
		&quot;Cust_Rating&quot;: 3.7
	},
	{
		&quot;Name&quot;: &quot;P2&quot;,
		&quot;ID&quot;: 2,
		&quot;Price&quot;: 1170,
		&quot;SalesCount&quot;: 718,
		&quot;Category&quot;: &quot;A&quot;,
		&quot;Cust_Rating&quot;: 3.8
	},
	{
		&quot;Name&quot;: &quot;P3&quot;,
		&quot;ID&quot;: 3,
		&quot;Price&quot;: 1090,
		&quot;SalesCount&quot;: 1253,
		&quot;Category&quot;: &quot;A&quot;,
		&quot;Cust_Rating&quot;: 0.5
	}
]

Project Structure looks like:
Project Structure

<strong>JsondbApplication.java</strong>

package com.saurabhsomani;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.saurabhsomani.domain.Product;
import com.saurabhsomani.service.ProductService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@SpringBootApplication
public class JsondbApplication {

	public static void main(String[] args) {

		SpringApplication.run(JsondbApplication.class, args);
	}

	@Bean
	CommandLineRunner runner(ProductService productService){ //will help us when the application starts up
		return args -&gt; { //functional interface
			//read json and write to db
			ObjectMapper mapper = new ObjectMapper();
			//We want a list of products
			TypeReference&lt;List&lt;Product&gt;&gt; typeReference = new TypeReference&lt;List&lt;Product&gt;&gt;(){};
			InputStream inputStream = TypeReference.class.getResourceAsStream(&quot;/json/product.json&quot;);
			try{
				//mapper helps us map json structure to the domain object
				List&lt;Product&gt; products = mapper.readValue(inputStream, typeReference);
				productService.save(products);
				System.out.println(&quot;Products Saved!&quot;);
			} catch (IOException e){
				System.out.println(&quot;Unable to save products: &quot; + e.getMessage());
			}
		};
	}
}

<strong>ProductController.java</strong>

package com.saurabhsomani.controller;

import com.saurabhsomani.domain.Product;
import com.saurabhsomani.service.ProductService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(&quot;/products&quot;)
public class ProductController {
    //no business logic in controller

    private ProductService productService;

    //constructor
    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    public ProductService getProductService() {
        return productService;
    }

    @GetMapping(&quot;/list&quot;)
    public Iterable&lt;Product&gt; list(){
        return productService.list();
    }

}

<strong>Product.java</strong>

package com.saurabhsomani.domain;

import lombok.AllArgsConstructor;
import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Data
@AllArgsConstructor
@Entity
public class Product {

    @Id
    @GeneratedValue( strategy = GenerationType.AUTO)
    private String name;
    private int id;
    private int price;
    private int salesCount;
    private String category;
    private double cust_rating;

    public Product(){

    }
}

<strong>ProductService.java</strong>

package com.saurabhsomani.service;

import com.saurabhsomani.domain.Product;
import com.saurabhsomani.repository.ProductRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductService {

    private ProductRepository productRepository;

    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public Iterable&lt;Product&gt; list(){
        return productRepository.findAll();
    }

    //to save one product
    public Product save(Product product){
        return productRepository.save(product);
    }

    //to save list of products
    public void save(List&lt;Product&gt; products) {
        productRepository.saveAll(products);
    }

}

<strong>ProductRepository</strong>

package com.saurabhsomani.repository;

import com.saurabhsomani.domain.Product;
import org.springframework.data.repository.CrudRepository;

public interface ProductRepository extends CrudRepository &lt;Product, String&gt;{

}

答案1

得分: 0

Product类中,您需要在与源JSON属性不完全相同但大小写不同的属性上添加Jackson的@JsonProperty注解。

public class Product {

    ...

    @JsonProperty("Name")
    private String name;

    @JsonProperty("Price")
    private int price;

    @JsonProperty("Cust_Rating")
    private double cust_rating;

    // 其他属性
}

附注:在除单元测试之外的命名中尽量避免使用下划线,并遵循Java代码约定(https://google.github.io/styleguide/javaguide.html)。

英文:

In Product class you need to add Jackson's @JsonProperty annotation on properties relevant to attributes of source JSON as they are not identical (but differently cased)

public class Product {

    ...

    @JsonProperty(&quot;Name&quot;)
    private String name;

    @JsonProperty(&quot;Price&quot;)
    private int price;

    @JsonProperty(&quot;Cust_Rating&quot;)
    private double cust_rating;

    // and others
}

P.S. try to avoid underscores in names outside of unit tests and stick to Java Code Conventions (https://google.github.io/styleguide/javaguide.html)

huangapple
  • 本文由 发表于 2020年7月27日 14:59:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63110192.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定