首页 > 解决方案 > Java GSON 错误:JSON 文档未完全使用

问题描述

所以我有一个 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());
        }


    }
} 

标签: javajsongson

解决方案


首先,您在 java 类中使用Department而不是Categories 。如我所见,它包含不同的字段。我相信您的问题出在读取文件的 json 文件或 Main 类中。使用 Guava 可以让您更轻松地阅读文件。查看我的代码:

产品.json

{
  "name": "MacBook",
  "price": 1299,
  "stock": 10,
  "picture": "macbook.jpeg",
  "categories": [
    {
      "id": 1,
      "name": "macbook"
    },
    {
      "id": 2,
      "name": "notebook"
    }
  ]
}

主类

package com.test;

import com.google.common.io.Resources;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) throws Exception {
        Gson gson = new GsonBuilder()
                .create();

        String products = Resources.toString(Resources.getResource("products.json"), StandardCharsets.UTF_8).trim();

        Product productObject = gson.fromJson(products, Product.class);

        System.out.println(productObject);
    }
}

输出是

Product{name='MacBook', price=1299, stock=10, picture='macbook.jpeg', categories=[Category{id=1, name='macbook'}, Category{id=2, name='notebook'}]}

推荐阅读