所以我有一个json文档,我想用不同的值来读取它,包括如下所示的数组
{ "name": "MacBook", "price": 1299, "stock": 10, "picture": "macbook.jpeg", "categories": [{"id": 1,"name": "macbook"},{"id": 2, "name":"notebook"}]}
我创建了几个pojo java类来读取它们:
1类(product.java)
package models;
import java.util.ArrayList;
public class Product {
String name;
int price;
int stock;
String picture;
public ArrayList<Categories> categories;
public Product(String name, int price, int stock, String picture) {
this.name = name;
this.price = price;
this.stock = stock;
this.picture = picture;
this.categories = new ArrayList<>();
}
public void setName(String name) {
this.name = name;
}
public void setPrice(int price) {
this.price = price;
}
public void setStock(int stock) {
this.stock = stock;
}
public void setPicture(String picture) {
this.picture = picture;
}
public void setCategories(ArrayList<Categories> categories) {
this.categories = categories;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public int getStock() {
return stock;
}
public String getPicture() {
return picture;
}
public ArrayList<Categories> getCategories() {
return categories;
}
@Override
public String toString() {
return "Product{" +
"productName='" + name + '\'' +
", productPrice=" + price +
", productStock=" + stock +
", productPicture='" + picture + '\'' +
", categories=" + categories +
'}';
}
}
2类(categories.java)读取数组
package models;
public class Categories {
private int id;
private String description;
public int getId() {
return id;
}
public String getDescription() {
return description;
}
public void setId(int id) {
this.id = id;
}
public void setDescription(String description) {
this.description = description;
}
public Categories(int id, String description) {
this.id = id;
this.description = description;
}
@Override
public String toString() {
return "Category{" + "id=" + id + ", description=" + description + '}';
}
}
这是主要的
package p3;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import models.Product;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
String fichero = "";
try (BufferedReader br = new BufferedReader(new FileReader("src/res/FitxersJSON/products.json"))) {
String linea;
while ((linea = br.readLine()) != null) {
fichero += linea;
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
Product productObject = gson.fromJson(fichero.toString(), Product.class);
System.out.println(productObject);
}
}
由于某种原因,当我执行main时,我得到了这个错误
Exception in thread "main" com.google.gson.JsonIOException: JSON document was not fully consumed.
at com.google.gson.Gson.assertFullConsumption(Gson.java:861)
at com.google.gson.Gson.fromJson(Gson.java:854)
at com.google.gson.Gson.fromJson(Gson.java:802)
at com.google.gson.Gson.fromJson(Gson.java:774)
at p3.Main.main(Main.java:42)
我尝试过格式化json文档,但看起来一切正常,因为我可以在每个循环中打印“linea”值来清晰地读取它。
先谢谢你。
[编辑]
我通过在json文件的开头和结尾添加“[”和“]”,并在除最后一行之外的所有行中添加“,”来解决这个问题。
package p3;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import models.Categories;
import models.Product;
import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class Main {
public static void main(String[] args) {
ex2_readProducts();
ex3_addProducts();
}
private static void ex2_readProducts() {
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<Product>>() {
}.getType();
String file = "";
try (BufferedReader br = new BufferedReader(new FileReader("src/resources/products.json"))) {
String linea;
System.out.println("*****************************Reading the JSON file*********************************");
while ((linea = br.readLine()) != null) {
file += linea;
}
Collection<Product> enums = gson.fromJson(file, collectionType);
int counter = 0;
for (Product r : enums) {
counter++;
System.out.println("Product nº: " + counter );
System.out.println(r);
}
System.out.println("Result: " + counter + " products read from the file" );
System.out.println("*****************************Finished reading the JSON file*********************************");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public static void ex3_addProducts() {
Gson gson = new Gson();
Categories c1 = new Categories(1, "tablet");
Categories c2 = new Categories(2, "game");
Categories c3 = new Categories(3, "phone");
Categories c4 = new Categories(5, "smartwatch");
Categories c5 = new Categories(9, " scooter");
Product p1 = new Product("ipad32", 1200, 23, "ipad32.jpg");
Product p2 = new Product("soccer 3000", 100, 500, "soccer.jpg");
Product p3 = new Product("pixel", 900, 900, "pixel.jpg");
Product p4 = new Product("mi watch", 300, 23, "miwatch.jpg");
Product p5 = new Product("mi scooter 365", 365, 23, "miscooter.jpg");
ArrayList<Categories> categoriesArrayList1;
categoriesArrayList1 = new ArrayList<>(Arrays.asList(c1, c3));
ArrayList<Categories> categoriesArrayList2;
categoriesArrayList2 = new ArrayList<>(Arrays.asList(c1, c2, c3));
ArrayList<Categories> categoriesArrayList3;
categoriesArrayList3 = new ArrayList<>(Arrays.asList(c1, c4, c3));
ArrayList<Categories> categoriesArrayList4;
categoriesArrayList4 = new ArrayList<>(Arrays.asList(c1, c3));
ArrayList<Categories> categoriesArrayList5;
categoriesArrayList5 = new ArrayList<>(Arrays.asList(c5, c1));
p1.setCategories(categoriesArrayList1);
p2.setCategories(categoriesArrayList2);
p3.setCategories(categoriesArrayList3);
p4.setCategories(categoriesArrayList4);
p5.setCategories(categoriesArrayList5);
Product[] productsArray = {p1, p2, p3, p4, p5};
try (BufferedWriter br = new BufferedWriter(new FileWriter("src/resources/products2.json"))) {
System.out.println("**********************Adding products to a new file:*********************************");
br.write("[");
br.newLine();
int counter = 0;
for (int i = 0; i < productsArray.length; i++) {
System.out.println("Product nº: " + (i+1) + '\n' + productsArray[i]);
String json = gson.toJson(productsArray[i]);
br.write(json);
if (i != productsArray.length - 1) {
br.write(",");
}
br.newLine();
counter = (i+1);
}
br.write("]");
System.out.println("Result: " + counter + " products added to the file" );
System.out.println("****************************Finished adding products*****************************");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
2条答案
按热度按时间eaf3rand1#
首先,在java类中使用department而不是categories。在我看来,它包含不同的字段。我相信你的问题出在json文件或读取该文件的主类内部。使用Guava让你更容易阅读文件。查看我的代码:
产品.json
主类
输出为
g2ieeal72#
我认为json的主要问题是
{"id": 1,"name": "macbook"}
但是在java类中Categories
你用private String description;
,json解析器应该如何理解这一点description
以及name
是同一个领域吗?在我看来,你应该试着用
name
代替description
,例如