Tips for converting a JSON map object into an array of objects using the Jackson library

Here is the JSON structure I am working with:

{
    "blabla": {
        "1": {
            "foo": "foo1",
            "bar": "bar1"
        },
        "22": {
            "foo": "foo22",
            "bar": "bar22"
        }
    }
}

This JSON represents a mapping of integers to objects.
I am interested in converting this JSON into an array of objects that match the following class structure:

class FooBar
{
    public int id;
    public String foo;
    public String bar;
}

Are there any methods to achieve this conversion without directly parsing the map and iterating over it?

Answer â„–1

Based on the provided json, it seems that the class structure would look something like this (...yes, your json cannot be parsed into your FooBar class directly. This is because the json indicates id as a key, whereas the FooBar class includes id as a member variable. Therefore, they are not directly convertible) :

class FooBar {                                             
    public String foo;                                     
    public String bar;                                     
};                                                         

class FooBarObject {                                       
    public HashMap<String, FooBar> blabla;                 
    public void setBlabla(HashMap<String, FooBar> blabla) {
        this.blabla = blabla;                              
    }                                                      
    public HashMap<String, FooBar> getBlabla() {           
        return blabla;                                     
    }                                                      
};                                                         

This code above serves as an illustration.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * Hello world!
 */
class FooBar {
    public String foo;
    public String bar;
};

class FooBarObject {
    public HashMap<String, FooBar> blabla;
    public void setBlabla(HashMap<String, FooBar> blabla) {
    this.blabla = blabla;
    }
    public HashMap<String, FooBar> getBlabla() {
    return blabla;
    }
};

public class App {

    static String target = ""
    + "{"
    + "    \"blabla\": {"
    + "        \"1\": {"
    + "            \"foo\": \"foo1\","
    + "            \"bar\": \"bar1\""
    + "        },"
    + "        \"22\": {"
    + "            \"foo\": \"foo22\","
    + "            \"bar\": \"bar22\""
    + "        }"
    + "    }"
    + "}";

    public static void main(String[] args) throws Exception {

    FooBarObject blabla = new FooBarObject();
    HashMap map = new HashMap<String, FooBar>();
    map.put("1", new FooBar());
    map.put("22", new FooBar());
    blabla.setBlabla(map);

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(blabla);

    System.out.println("--- BEGIN ---");
        System.out.println(json);
    System.out.println("--- END ---");

    blabla = mapper.readValue(target, FooBarObject.class);
    System.out.println("--- BEGIN ---");
    for ( Map.Entry<String, FooBar> entry : blabla.blabla.entrySet() ) {
        String internal = mapper.writeValueAsString(entry.getValue());
        System.out.println(entry.getKey() + ": " + internal);
    }
    System.out.println("--- END ---");
    }
}

However, there might be an issue already present... Are you sure you want to use an Array instead?

{
    "blabla": [
        "1": {
            "foo": "foo1",
            "bar": "bar1"
        },
        "22": {
            "foo": "foo22",
            "bar": "bar22"
        }
    ]
}

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

Utilizing JSON and forms within Visual Studio environment for seamless development

When I work on Visual Studio and create a form, the common language RunTime Support automatically changes to /clr. However, when I try to add json libraries, I encounter the following error: is not supported when compiling with /clr or /clr:pure Switc ...

Using Node.js to write data to a JSON file

Currently, I am working on a program that scans through an array containing numerous links. It reads through each link, extracts specific text, and then stores it in an output file as JSON. However, I am facing an issue with formatting the JSON file. The ...

Modify each item/entry within a 90-gigabyte JSON file (not necessarily employing Python)

I'm facing a challenge with a massive 90G JSON file containing numerous items. Here's a snippet of just three lines for reference: {"description":"id1","payload":{"cleared":"2020-01-31T10:23:54Z","first":"2020-01-31T01:29:23Z","timestamp":"2020- ...

Choosing an Array of Integers in PostgreSQL: A Guide

My goal is to extract arrays of integers from a table in this format: [1, 2, 3] I attempted the following query: (SELECT array_to_json(array_agg(row_to_json(s))) FROM( SELECT specialty FROM talent_specialty WHERE userid = 840 )s); This is the result r ...

Python script to retrieve matching values on the same level of a JSON structure

I am facing a dilemma with my Python code that involves making an API call and receiving JSON data. My goal is to create a list in Python containing item IDs along with their matching descriptions. Below is a simplified version of the issue I am currently ...

In the realm of Swift programming, lies the intriguing task of parsing a JSON file that is securely stored on a

I am new to the concept of JSON parsing. Currently, I am attempting to retrieve data from a local JSON file in my Swift project. I have successfully implemented the code to fetch the data. However, I am facing difficulties in creating an array of objects b ...

Pass data from PHP to JS after triggering AJAX communication

*Updated with full code example, after receiving feedback I decided to share a sample of the code that is giving me trouble. Essentially, I am trying to achieve the functionality where clicking on a link in the HTML will submit a form to called.php and dis ...

Enhance User Experience by Dynamically Updating Google Maps Markers with Custom Icons Using Django and JSON

Hey StackOverflow Community! I've been working on creating a web interface to showcase the communication statuses of different network elements. I'm almost done with the challenging part that I had been procrastinating. To add an awesome touch, ...

Creating HTML within a Servlet by incorporating additional quotation marks

Currently, I'm attempting to construct some HTML markup within a Spring controller. Here is a snippet of the code: append(sb ,"<div class=&quot;myDiv&quot;>"); This code snippet ends up generating the following HTML source in the brows ...

Is submitting with JQuery always a hit or miss?

Hey there, I'm currently working on a problem and could use some help. I seem to be having trouble getting inside my function for form submission in JQuery. Despite setting up console.logs, it appears that my code never reaches the first function. Can ...

Built-in Handlebars helper for nested iteration - no results displayed

I'm currently facing an issue with using an iteration helper within another one. Strangely, the inner helper isn't producing any output. Here's a snippet of the handlebars template I'm working with: {{#people}} <h4>{{firstNa ...

Pass the JSX data as JSON from the Express backend and showcase it as a component in the React frontend

I am currently developing a basic react front-end paired with an Express backend. Is it possible for me to have express send JSX data as JSON so that I can fetch it in react and utilize it as a component? Right now, I am sending JSON data and successfully ...

Troubleshooting the Selenium Protractor Webdriver-Manager Update Problem on Ubuntu

Upon running the webdriver-manager update command, I encountered the following error message. /usr/lib/node_modules/protractor/node_modules/webdriver-manager/built/lib/cmds/start.js:60 if (path.isAbsolute(options[Opt.OUT_DIR].getString())) { ...

Tips for creating Java code that generates visually appealing colored HTML from JSON data include:1. Use libraries like Gson or Jackson

On certain pages dedicated to our API, such as for sales, we want to showcase JSON examples. We are looking for a nicely formatted display with color-coded spans. While the option of using the JavaScript code prettifier from this archived and unmaintaine ...

Moving the query function from routes to the repository in Laravel

Greetings! I am relatively new to the world of Laravel and I am in the process of setting up a repository to consolidate repeated database calls. It seemed logical to centralize these calls for easier reference. Currently, I have a chained select feature t ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Develop an array of JSON Objects within a Java environment

My task involves handling a CSV file with 10 columns and multiple rows. The goal is to convert each row into a JSON object. An example of the file structure is as follows: Name, Age, Address..........and other columns ABCD, 23 , HOME.............and other ...

Guide to importing a JSON file in a Node.js JavaScript file

I am trying to incorporate a JSON file into my JavaScript code in a Node.js application. I attempted to include it using the "require();" method, but encountered an issue: "Uncaught ReferenceError: require is not defined". ...

The d3 hierarchy possesses the capability to compute the average values of child nodes

Looking for a solution with d3 visualization that involves averaging up the value of score on the lowest nodes and dynamically adding that average to the parent node above. It seems like there isn't an easy method in d3 for this task. The desired outc ...

"Discrepancy in results between JSON stringify and JavaScript object conversion

I need to save this object in a database, but first I have to send it to the backend. Recorder {config: Object, recording: false, callbacks: Object, context: AudioContext, node: ScriptProcessorNode…} However, after using JSON.stringify(recorder) The r ...