Create a new JSON file and add data using ObjectMapper

My current project involves delving into Jackson to gain a better understanding of how it works. I am in the process of creating a simple program that can both read from and write to a file, specifically storing JSON data in it. This project revolves around maintaining a list of shopping lists, each consisting of a store name and items related to that store.

However, I have encountered an obstacle while attempting to append new entries (in JSON format) to the end of the file. Here's what I have managed to accomplish so far; feel free to skip over the initial part as it merely includes a basic console scanner for user input:


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();
    }

    // Additional methods omitted for brevity...

}

I am keen on continuing to utilize the ObjectMapper functionality since my goal is to learn more about Jackson. However, I haven't yet discovered a way to effectively append new data. Any suggestions or insights are highly appreciated!

Answer ā„–1

In order to add content, the Streaming API must be utilized to initialize a JsonGenerator; thereafter, this generator can be passed to an ObjectMapper for writing. Here is an example:

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

Answer ā„–2

If you need to add new objects to a JSON file without losing existing data, you can use the following method. This code snippet reads an existing JSON file and appends new Java objects to it.

public static void appendWriteToJson() {

    ObjectMapper mapper = new ObjectMapper();

    try {
        // Store object as 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();
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an issue with mapping data from a controller to a view in Angular.js

Currently, my application consists of only three small parts: a service that makes an http call to a .json file, a controller that receives data from the service and sends it to a view. Everything was working fine when I hard coded the data in my service. ...

Update JSON data in ng-blur event using AngularJS

Could you offer some guidance on how to push the content from a text box into JSON when I click outside of the box? Below is the code for my text box: <input type="text" name="treatmentCost" class="form-control" ng-model="addTemplate" /> And here i ...

I'm just starting out with jQuery and JSON and could use some assistance with formatting the string, specifically so I can properly iterate through it

This is the controller. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> @RequestMapping("/getDropDownAjax") public void fetchData(HttpServletRequest req,HttpServletResponse resp){ System.out.println ...

angular data binding returning the identifier instead of the content

I have been dealing with managed fields retrieved from a web server in the following format: { "fields":{ "relationshipStatus":[ { "fieldId":4, "name":"Committed" }, { "fieldId":2, ...

Customizing response headers in vanilla Node.js

My Node.js setup involves the following flow: Client --> Node.js --> External Rest API The reverse response flow is required. To meet this requirement, I am tasked with capturing response headers from the External Rest API and appending them to Nod ...

Using JavaScript to parse JSON data generated by PHP using an echo statement may result in an error, while

I am facing an issue with parsing a JSON string retrieved from PHP when the page loads. It's strange that if I send an AJAX request to the same function, the parsing is successful without any errors. The problem arises when I attempt to do this: JSON ...

JS/Apps Script: Passing object and its keys as function parameters

When working with Google Apps Script, I have a specific task that involves looping through data and writing only certain keys to a sheet. I want this looping operation to be done in a separate function rather than directly in the main function, as it will ...

Sending information to a Flask application using AJAX

Currently, I am working on transferring URLs from an extension to a Flask app. The extension is able to access the current URL of the website. I have set up an AJAX request to connect to Flask, and the connection is successful. However, when trying to send ...

Utilize API to import sunrise and sunset times based on specific coordinates directly into a Google Sheet

After countless hours of trying to crack this code, Iā€™m faced with a final hurdle. The challenge lies in parsing the output from the and storing either the sunrise or sunset time into a variable that can be exported as a result in a Google Sheet. The u ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

Error: Unsupported Media Type when attempting to send JSON data from an AngularJS frontend to a Spring controller

Below is the controller function code snippet @RequestMapping(value = "/logInChecker", method = RequestMethod.POST, consumes = {"application/json"}) public @ResponseBody String logInCheckerFn(@RequestBody UserLogData userLogData){ Integer user ...

The function json.stringify fails to invoke the toJson method on every object nested within the main object

When using IE 11, I encountered an issue where calling Stringify on my objects did not recursively call toJson on all objects in the tree. I have implemented a custom toJson function. Object.prototype.toJSON = function() { if (!(this.constructor.name == ...

Comparison of efficiency in declaring JSON data using JSON.parse versus an object literal

In a recent video from the 2019 Chrome Dev Summit titled "Boosting App Speed with JSON.parse", it was revealed that utilizing JSON.parse with a string literal instead of an object literal can result in a significant enhancement in speed. The official Googl ...

Error: Trying to send FormData to ajax results in an Illegal Invocation TypeError being thrown

Successfully sending a file to the server for processing using the code below: var formData = new FormData(); formData.append('file', $('#fileUpload')[0].files[0]); options = JSON.stringify(options); // {"key": "value"} $.ajax({ ...

Analyzing Dynamic Content

Currently, I am engaged in content parsing and have successfully executed a sample program. To demonstrate, I have utilized a mock link which you can access below: Alternatively, you can click on this link: Click Here In the provided link, I have parsed ...

Updating JSON objects in jQuery with string keys

I have an array variable containing JSON data and I need to update specific values within the array using string keys. Here is a snippet of what my array looks like: { "all": [ { "image":{ "URL":"img/img1.jpeg", ...

Unforeseen alterations in value occur in JavaScript when converting to JSON format

Having trouble generating a gantt chart from a JSON string, specifically with parsing the JSON string into a JSON object. I have a variable myString containing a JSON string that looks like this: {"c": [{"v": "496"}, {"v": "Task name 1"}, {"v": "9, "}, { ...

Receiving JSON using Javascript and vue.js

When attempting to fetch json data in my vue.js application, I use the following code: new Vue({ el: 'body', data:{ role: '', company: '', list:[], ...

Troubleshooting JavaScript Date Problem with Internet Explorer 7

When I retrieve a Date from a web method, it comes in the format of "Mon Sep 30 07:26:14 EDT 2013". However, when I try to format this date in my JavaScript code like this: var d= SomeDate.format("MM/dd/yyyy hh:mm:ss tt"); //Somedate is coming from the we ...

Managing additional components in request JSON when communicating with DialogFlow, previously known as Api.ai

My current challenge involves enhancing the information sent in a JSON request from my application to DialogFlow. While I am familiar with triggering events to send data calling an intent through the method described in Sending Parameters in a Query Reques ...