convert JSON to Java object using GSON with a map

Here is the structure of my Java POJO:

public class MyPersonTO{
  String name;
  String surname;
  Map<String, Double> categories;

}

Currently, I am using the Gson library, but I'm uncertain about the formatting of my JSON string and the object it should be created from. I am using `JSON.stringify` on a JavaScript object that has two strings and an array of objects. Here is a simplified version in pseudo code:

var json = [];
jsonObject = new Object();
jsonObject.name = "testname"
jsonObject.surname = "testsurname"
var categories = [];

for(index=0; index < 10; index++){
    var category = new Object();
    category.key = getKey();
    category.value = index;
    categories.push(category);
}
jsonObject.categories = categories;
json.push(jsonObject);
json = JSON.stringify(json); //converts JSON object for submission

In my Java code, I am using the following:

Type listType = new TypeToken<List<MyPersonTO>>() {}.getType();
List<MyPersonTO> myPersonList  = new Gson().fromJson(jsonString, listType);

If you have any advice or suggestions on this matter, please feel free to share. Thank you!

Answer №1

I'm sorry, your question is a bit unclear to me. However, I believe the JSON representation of one of those objects would resemble something like this:

{
  "name": "Bob",
  "surname": "Scum",
  "categories": {
    "whatever": 22.5,
    "balloons": 107.0023,
    "zebras": -10299.01
  }
}

edit — Regarding the changes in your question: The "categories" object should not be an array, but instead a plain object like in my example. I assume that's how it should be formatted. While I haven't checked the specifics of this "gson" you mentioned, I would be surprised if it expects Java Map instances to be represented as arrays (so much so that I would consider using another library).

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

Enhance your viewing experience by magnifying a specific element, all while maintaining full control to navigate

Is it possible to create a zoom effect on a webpage that focuses on one specific element while still allowing for navigation and scrolling? I have searched online for plugins like Fancybox and Zoomooz, but none of them offer the functionality I need. I sp ...

Ways to bring GIFs into NextJS

I am currently working on my portfolio website using Nextjs and I would like to incorporate gifs into the site. However, I have been struggling to figure out how to do so. Below is the code that I have been working with: https://i.stack.imgur.com/zjoiD.pn ...

Adjusting the display of HTML elements depending on geolocation authorization

I am currently facing an issue with my HTML code where I want to show an element only if the user declines to share their location with the browser. However, my code is not functioning as expected when the user rejects the location request. On the other ha ...

Tips for implementing an element onClick change within a Redux container using React.js

After coming across a similar question by another user on this link, I found the answer quite clear. However, if you're dealing with a redux container, the states are transformed into props via the mapStateToProps function. So, my query is: how shoul ...

Utilize the Google Maps API to align an SVG symbol with the direction of an aircraft's

I have been struggling to update the rotation of the Google Maps API SVG aircraft symbol to display the correct heading as it moves. Although it initially loads with the correct heading, I can't seem to figure out how to dynamically update it. I' ...

The power of relative URLs in AJAX calls

Why does Javascript handle relative URLs differently than standard HTML? Consider the URL provided: http://en.wikipedia.org/wiki/Rome. Launch a Firebug console (or any other Javascript console) and type in the following: var x = new XMLHttpRequest(); x.op ...

Iterate through the URL parameters and store them in the database

I need to efficiently loop through all my post requests and aggregate them collectively. What is the most effective approach for achieving this? Below is the Form structure along with the data I receive: var Form = new Schema({ title: { type: ...

What is the method for pulling information from MySQL and presenting it on a website using Node.js?

Currently, my goal is to retrieve data from MySQL and showcase it on my HTML page. The code snippet in server.js looks like this: const path = require('path'); const express = require('express'); const bodyParser = require("body-pa ...

The JQuery .replaceWith method exclusively offers unprocessed HTML content

I'm experiencing a minor issue with my ajax response where it returns raw html and does not execute any scripts, resulting in the jquery ui scripts not being executed. Here are some details: I am currently working with ASP.NET MVC and I need to comm ...

Mac OS reports an Illegal instruction: 4 error when running NodeJS

Each time I try to execute my program, it gives me an Illegal instruction: 4 error without any clue as to why. The code snippet in question: glob('/path/music/*.mp3', function(error, files) { for(var i = 0; i < files.length; i++) { songs ...

Leveraging the power of JavaScript and possibly regular expressions to extract numerical values from a

I am attempting to extract a variable number from the text provided in the following example: Buy 5 for € 16.00 each and save 11% Buy 50 for € 15.00 each and save 17% Buy 120 for € 13.00 each and save 28% Buy 1000 for € 10.00 each and save 45% Th ...

The Python script designed for GCS that previously accepted arguments in the terminal and utilized json.loads() has suddenly ceased to function

I am currently in the process of uploading files to GCS (Google Cloud Storage) and my script was working perfectly fine. However, when I try to run it in Terminal using the command python uploadtogcs.py 'C:/Users/AS/Documents/GCSUploadParameters.json& ...

Scriptmanager and Rokbox clash in a heated confrontation

I'm having trouble getting RokBox to display images on my webpage because the asp:ScriptManager seems to be causing some issues. After trying to troubleshoot, I found that when I remove the following code: <asp:ScriptManager ID="ScriptManager1" r ...

What is the Best Way to Send JavaScript Variables to MYSQL Database with PHP?

I am having trouble sending my variable to a MySQL database. The database only displays the variable when using the HTML input tag. The error message I received was "Undefined index: rate & amount." Seeking assistance to resolve this issue. Thank you! ...

Transferring intricate data gracefully through the URL

I'm considering using something along the lines of: <script src="http://www.example.com/?key={'param':'value'}"> As illustrated in the example above, a JSON formatted string is being passed through the src URL. However, thi ...

Creating a JSFiddle with sprites using source and image files from Github with THREE.JS - a step-by-step guide

Greetings! I am currently working on creating a JSFiddle based on the official THREE.js HUD Sprites example. However, I am facing an issue where the sprite images do not seem to load or apply using the URLs specified in the original file:- //... URL' ...

The JSON response is displaying [object object] instead of an array

I am currently facing an issue with my Sencha touch app where the json data I am feeding into it is not returning the image URLs as expected. Instead, it is showing me "[object Object]" when I console.log the "images" property. Here is a snippet of the js ...

`Navigating through database structures using node js`

When it comes to interpreting a Database {} object in JavaScript, I am currently working on back end scripts for validating a registration form. Specifically, I need to make sure that the username and email being used for registration are not already taken ...

The Ionic tab is already finished displaying even before the data has completed loading

Creating a favorites section for a vouchers app has proven to be slightly challenging. When attempting to retrieve the current user's favorite vouchers and display them using ngFor in the HTML, I encountered an issue. The very first time I open the fa ...

Unraveling the mystery: How does JavaScript interpret the colon?

I have a quick question: When I type abc:xyz:123 in my GoogleChrome browser console, it evaluates to 123. How does JavaScript interpret the : symbol in this scenario? ...