Converting a Java map into JSON and then into a Typescript map

On the server side, I have a Java object that includes a HashMap. My goal is to serialize it into JSON, send it back to my Angular2 client, and utilize it as a Map/Dictionary there.

The class structure is as follows:

public class FileUploadResult {
    String timestamp;
    String message;
    String status;
    HashMap<String, String> parameters;

    public FileUploadResult(String status, String message, String timestamp, HashMap parameters) {
        this.status = status;
        this.message = message;
        this.timestamp = timestamp;
        this.parameters = parameters;
    }

}

Upon receiving the JSON on the client side, it looks like this:

{"timestamp":"","message":"Test","status":"1","parameters":{"myKey":"Value","mySecondKey":"Another Value"}}

My Angular2 http call for handling this data is as follows:

this.http.post(this.uploadURL, formData).map((res:Response) => res.json() as FileUploadResult).catch(this.handleError); 

Implementation of FileUploadResult in the client-side code appears as:

export class FileUploadResult {
    status: string;
    timestamp: string;
    message: string;
    parameters: Map<string, string>;

    constructor() {
        this.parameters = new Map<string, string>();
    }

    addParameter(key: string, value: string) {
        this.parameters.set(key, value);
    }

    getParameters() {
        return this.parameters;
    }
}

After using "as FileUploadResult" in the http.map call, the expectation was to access

result.getParameters().get("myKey")
. However, currently only result.parameters.myKey is functioning. Is there a way to correctly cast the JSON object to FileUploadResult along with an Angular2 map?

Answer №1

When you call res.json(), it returns a javascript object that can be accessed as follows:

let json = res.json();
console.log(json["timestamp"]);
console.log(json.message);

In TypeScript, the way to define such an object is by using an interface (or type alias):

interface APIResponse {
    timestamp: string;
    message: string;
    status: string;
    parameters: { [name: string]: string };
}

If you want to convert this object into a custom class, you would need to create something like:

class APIData {
    status: string;
    timestamp: string;
    message: string;
    parameters: Map<string, string>;

    constructor(json: APIResponse) {
        this.status = json.status;
        this.timestamp = json.timestamp;
        this.message = json.message;

        this.parameters = new Map<string, string>();
        Object.keys(json.parameters).forEach(key => {
            this.addParameter(key, json.parameters[key]);
        });
    }

    addParameter(key: string, value: string) {
        this.parameters.set(key, value);
    }

    getParameters() {
        return this.parameters;
    }
}

(for full code implementation visit)this link)

Answer №2

class FileUploadResult {
    data: Record<string, string> = {};

    addData(key: string, value: string) {
       this.data[key] = value;
    }
}

Here is an example of how to use it:

const file = new FileUploadResult();
file.addData('username', 'john_doe');
console.log(file.data);   // will display {username: "john_doe"}

Check out the documentation for more information.

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

Using a dropdown list to filter values in a table with Angular ngBootstrap

Seeking assistance with filtering table values based on the selected filter. I plan to utilize this ngbDropdown as my filter. If I choose company A, only entries related to company A will be displayed in the table. I am unsure about how to connect the f ...

Using Typescript to replicate Object.defineProperties

Is there a way to emulate Object.defineProperties from JavaScript in Typescript? I am interested in achieving something similar using the syntax of Typescript: Object.defineProperties(someObject.prototype, { property: {get: function() { return v ...

Enhance User Experience - Automatically highlight the first element in Prime NG Menu when activated

I have been working on transitioning the focus from the PrimeNG menu to the first element in the list when the menu is toggled. Here is what I've come up with: In my template, I added: <p-menu appendTo="body" #menu [popup]="true&quo ...

What is the process for converting a multidimensional array from PHP into JavaScript?

Recently, I've been experimenting with dygraph. To populate my graph, I fetch data via an ajax call and then need to convert the returned JSON array into a JavaScript array. My dygraph options are set up like this: series = { sample1: { ...

Discovering errors within a reactive form in Angular using a loop to iterate through the FormArray

I am currently utilizing Angular CLI version 16.2.1. As I progress through a course, I am working with reactive forms. In a list of 'Recipes', I aim to include a Recipe with various inputs and a collection of ingredients. However, I am encounter ...

Guide to Using Templates to Publish an API in WSO2 API Manager

Recently, I have been exploring the capabilities of wso2 API Manager 1.8.0 to convert a back end (http/post) system into a REST API. After successfully getting it up and running, I found myself having to manually tweak the API configuration through the Ser ...

The most effective method for transferring values from PHP to Javascript

Currently, I am in search of the most effective way to transfer data such as arrays, objects, and JSON values from PHP to JavaScript. Up until now, I have only come across the following method: PHP - json_encode(value); JavaScript - eval() Anot ...

A guide to resolving the Angular 11 error of exceeding the maximum call stack size

I am currently working with 2 modules in Angular 11 CustomerModule AccountingModule I have declared certain components as widget components in these modules that are used interchangeably: CustomerModule -> CustomerBlockInfoWidget AccountingModule -&g ...

Delete an entry in a singular mapping in a one-to-one connection [TypeORM]

Is there a way to remove an index from a one-to-one relationship in TypeORM? @OneToOne(() => Customer, { cascade: true }) @JoinColumn({ name: 'customer', referencedColumnName: 'uid' }) customer: Customer I searched the d ...

Unable to redirect to another component using Angular route navigation

I recently started working with Angular and I'm currently building an Angular 4 app. I'm facing an issue where I'm trying to navigate from a module component to a layout component when a button is clicked, but the navigation is not working. ...

What steps should I take to eliminate the npm error from appearing in the protractor's logs whenever a spec fails?

I recently began using Protractor with Jasmine for testing an Ionic2 application. However, I have encountered two major issues that I have been unable to resolve despite extensive research: 1.)Whenever any of my specifications fail during testing, the err ...

What is the most optimal method for formatting JSON in Spray JSON?

I am working with a case class in Scala case class Employee(designation: Int, name: String) Now I need to create a JSON format for it using Spray. There are two different methods of achieving this. implicit lazy val employeeProtocol: RootJsonFormat[Emp ...

How can I create a customized scrollbar for a div element in an Angular 2.0 CLI project?

I am attempting to create a sleek horizontal scroll bar within one of my div elements, similar to the example shown here: https://i.stack.imgur.com/ziWhi.png My project is based on the angular2 CLI. Progress so far: I came across this package angular2-s ...

Struggling to obtain a json response using Retrofit

When using retrofit 1.9.0, I attempted the code below to retrieve a JSON formatted response: public void Execute(String email, String password, Callback<User> callback) { final Callback<User> cb = callback; RestAdapter restAdapter = bu ...

What is the best way to distinguish shared services from other services in Angular 6 and above?

There was a time when I frequently heard the term "shared services" in relation to sharing data between unrelated components in Angular. However, I started questioning whether every service is actually classified as a shared service or not. If it is cons ...

Unable to obtain the selection from the dropdown menu

I am currently populating data from a JSON file into a dropdown list. The code snippet I am using for this task is shown below: $(function() { $('#productList').append($('<option/>').attr("value", key).text(data[k ...

Truncating Rails bigint with as_json

When models have bigint columns with values such as 1456299399553483799, they often get converted to slightly different numbers like 1456299399553483800 when using the as_json method. Is there a simple or predefined method to automatically convert these b ...

Faulty deduction can occur when implementing the return statement in an identity function, or when incorporating an optional parameter

Encountering strange behavior while working on identity functions in a wizard system schema. Using a constrained identity function for inference is causing issues with one property that cannot be inferred when using the following: When the return value fr ...

Customized Menu Options for Different User Roles

Exploring the realms of .NET and Angular development has been an exciting journey for me. However, I've hit a roadblock concerning role-based menu items. While the routing is set up correctly to block unauthorized access, the challenge lies in hiding ...

I can't figure out why I'm getting the error message "Uncaught ReferenceError: process is not defined

I have a react/typescript app and prior to updating vite, my code checked whether the environment was development or production with the following logic: function getEnvironment(): "production" | "development" { if (process.env.NODE_E ...