有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ObjectMapper追加文件JSON

试图了解一些关于Jackson的信息,所以我正在编写一个简单的程序,读取一个文件/创建一个文件以在其中存储一些JSON。从Jackson的网站上,我了解了如何从文件中读写,但就我的初级程序而言,我还想附加。我基本上是想储存一份购物清单。有一个购物清单对象,它有商店名称和该商店的商品

问题是我无法找到一种方法将另一个条目附加到文件末尾(JSON格式)。以下是我目前正在处理的问题,您可以忽略第一个问题,这只是一个愚蠢的控制台扫描仪请求输入:

    public class JacksonExample {

    static ObjectMapper mapper = new ObjectMapper();
    static File file = new File("C:/Users/stephen.protzman/Desktop/user.json");
    static List<ShoppingList> master = new ArrayList<ShoppingList>();

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        boolean running = true;
        while (running) {
            System.out.println("[ 1 ] Add a new shopping list");
            System.out.println("[ 2 ] View all shopping lists");
            System.out.println("[ 3 ] Save all shopping lists");
            int choice = Integer.parseInt(in.nextLine());
            switch (choice) {
            case 1:
                getNewList();
            case 2:
                display();
            case 3:
                running = false;
            }
        }
        in.close();
    }

    public static void getNewList() {
        boolean more = true;
        String store, temp;
        List<String> items = new ArrayList<String>();
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the store: ");
        store = s.nextLine();
        System.out.println("Enter each item [If done type 'DONE'] :");
        while (more) {

            temp = s.nextLine();
            if (temp != null) {
                if (temp.toUpperCase().equals("DONE")) {
                    more = false;
                } else {
                    items.add(temp);
                }
            }

        }
        save(store, items);
        s.close();

    }

    public static void display() {
        try {
            ShoppingList list = mapper.readValue(file, ShoppingList.class);
            System.out.println(mapper.defaultPrettyPrintingWriter()
                    .writeValueAsString(list));

        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void save(String store, List<String> items) {
        //load in old one
        try {
            ShoppingList list = mapper.readValue(file, ShoppingList.class);
            System.out.println(mapper.defaultPrettyPrintingWriter()
                    .writeValueAsString(list));

        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //add to end of older list
        ShoppingList tempList = new ShoppingList();
        tempList.setStore(store);
        tempList.setItems(items);

        master.add(tempList);

        try {

            mapper.writeValue(file, master);


        } catch (JsonGenerationException e) {

            e.printStackTrace();

        } catch (JsonMappingException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }
    }

}

我想继续使用ObjectMapper(考虑到我正在学习Jackson),我只是还没有找到一种附加的方法。有什么想法吗


共 (2) 个答案

  1. # 1 楼答案

    下面的方法可用于以追加模式将对象写入json文件。它首先读取现有的json文件,并将新的java对象添加到json文件中

    public static void appendWriteToJson() {
    
        ObjectMapper mapper = new ObjectMapper();
    
        try {
            // Object to JSON in file
            JsonDaoImpl js = new JsonDaoImpl();
            URL resourceUrl = js.getClass().getResource("/data/actionbean.json");
            System.out.println(resourceUrl);
            File file = new File(resourceUrl.toURI());
    
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true))); // append mode file writer
    
            mapper.writeValue(out, DummyBeanObject);
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
  2. # 2 楼答案

    要附加内容,您需要使用流式API创建JsonGenerator;然后您可以将这个生成器交给ObjectMapper进行写入。比如:

    JsonGenerator g = mapper.getFactory().createGenerator(outputStream);
    mapper.writeValue(g, valueToWrite);
    // and more
    g.close();