【问题标题】:ObjectMapper append file JSONObjectMapper 附加文​​件 JSON
【发布时间】:2015-03-12 19:03:52
【问题描述】:

想了解一些关于 Jackson 的信息,所以我正在编写一个简单的程序来读取文件/创建一个文件以在其中存储一些 JSON。从杰克逊网站上,我知道了如何从文件中读取和写入,但对于我的基本程序,我也想追加。我基本上是在尝试存储购物清单。有一个购物清单对象,其中包含商店名称、该商店的商品。

问题是我无法想办法将另一个条目附加到文件末尾(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)我只是还没有找到一种追加方法。有什么想法吗?

【问题讨论】:

    标签: java json file io jackson


    【解决方案1】:

    要追加内容,需要使用 Streaming API 创建JsonGenerator;然后你可以把这个生成器给ObjectMapper写信。所以像:

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

    【讨论】:

    • 不知道为什么ObjectMapper作者从来没想过提供一个append方法?!
    • 从 API 的角度来看有更好的方法; mapper 现在有ObectMapper.writeValues(),它返回为追加设计的东西。 append() 方法就 API 设计而言无法正常工作。
    【解决方案2】:

    以下方法可用于以追加模式将对象写入 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();
        }
    }
    

    【讨论】:

    • 请稍微解释一下为什么这段代码会对 OP 有所帮助。
    • 什么是JsonDapImp类???你没有定义它!
    猜你喜欢
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多