Change Json data into a TypeScript class [ts]

I have the following JSON data:

{"mapData":{"test":"success","publicKey":""},"statusCode":200,"message":null}

How can I convert this JSON to a TypeScript class?

The mapData contains anonymous values:

  • It may be
    {"test":"success","publicKey":""}
  • Or it may be
    {"test":"success","publicKey":"","anotherKey":"anotherValue"}

So, how do we convert this JSON to a TypeScript object?

{"mapData":{"test":"success","publicKey":""},"statusCode":200,"message":null}

Here is an example of my TypeScript demo:

export class GenericResponse {

 mapData: any;
 statusCode: number;
 message: string;
}

Below are the Java classes I used to convert Object to JSON:

/**
  * Author: Atwa
  * Date: Jul 2, 2018
  */
 public class Response {

private Map<String, Object> mapData = new HashMap<>();

private int statusCode = 0;

private String message;


public Map<String, Object> getMapData() {
    return mapData;
}

public void setMapData(Map<String, Object> mapData) {
    this.mapData = mapData;
}

}

Answer №1

Below is the method I attempted:

  export class GenericResponse {

 mapData: any;
 statusCode: number;
 message: string;
 }

The file test.json contains the following data:

   {"mapData":{"test":"success","publicKey":""},"statusCode":200,"message":null}

In the TypeScript file:

   import { Component, OnInit } from '@angular/core';
   import { Http, RequestMethod, Response, Headers, RequestOptions, 
  RequestOptionsArgs } from '@angular/http';

     import {GenericResponse} from  "../../model/genericResponse.model";
  export class genericSerivice implements onInit{

  genericResponse:GenericResponse;
  mockTesturl="assets/data/test.json"

  public getGenericResponse():  Observable<GenericResponse>{

   ngOnInit(){

   this.getGenericResponse()
  }

  let params: RequestOptionsArgs = {
     headers: new Headers({
    url: this.mockTesturl,
    method: RequestMethod.Get,
    '_id': new Date().getTime(),
    'Cache-Control': 'no-cache',
    'Pragma':'no-cache',
    })
   };

    return this.http.get(this.mockTesturl, params)
  .pipe(map(res => this.extractGenericResponse(res)),
   catchError((error: any) => {
    if (error.status === 500) {
      return Observable.throw(new Error(error.status));
    }
    }))
  }

  private extractGenericResponse(res: any) {
 this.genericResponse = res;
}

https://i.sstatic.net/FZg8c.jpg

I hope this explanation is useful.

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

Display a single item from nested objects using ng-repeat

Imagine having an object where the keys represent different products and the values consist of objects with keys representing price points at which those products were sold, along with corresponding amounts sold. For instance, if you sold 10 widgets at $1 ...

Ways to showcase an array with HTML content in AngularJS without using ng-repeat

Can someone help with this coding issue? "elements" : ["<p>Element 1</p>","<span>Element 2</span>"] I want to achieve the following output: <div id="wrapper"> <p>Element 1</p> <span>Element 2</s ...

Achieving a successful 200 response from CORS in node-http-proxy for OPTIONS requests

I'm currently working on getting a web page up and running on :9000 to send a request to a reverse proxy operating in node on :8080 so that it can accept requests as if they were from the same domain. I've discovered that because different ports ...

Custom component not rendering expected CSS style

I have successfully developed a custom web component without using any framework. I then proceeded to populate it with content from a template tag. Although I was able to manipulate the content using JavaScript, I encountered difficulties when trying to m ...

retrieving the chosen information from the JcomboBox

Having trouble saving the user's selection as a string for further use in the code. I'm unable to retrieve the data selected by the user and unsure if I'm approaching it correctly. The commented code near the bottom of the script shows where ...

Utilizing Jackson to map JSON data fetched from a URL

After fetching a JSON string from a URL, I am interested in mapping only a specific array of items using the Jackson library. ObjectMapper mapper = new ObjectMapper(); Map<String,Object> map = mapper.readValue(new URL(urls.get(i)), Map.class); Upon ...

Importing dynamically into Ionic 2 from locations other than the "node_modules" directory

I've recently reviewed the documentation for ModuleResolution in TypeScript on this page: https://www.typescriptlang.org/docs/handbook/module-resolution.html#node My understanding is that all files I wish to import must reside within the node_modules ...

Getting the value of "Page=?" from the href attribute in an HTML tag can be done using Selenium Webdriver and Java

I am looking to extract the value "page = ?" from a specific "href" tag in the HTML code below. I need this value for my Selenium WebDriver script so that my loop can iterate up to page 53. Can someone guide me on how to retrieve the "page =" value mentio ...

Angular 6 issue: Data not found in MatTableDataSource

Working on implementing the MatTableDataSource to utilize the full functionality of the Material Data-Table, but encountering issues. Data is fetched from an API, stored in an object, and then used to create a new MatTableDataSource. However, no data is b ...

Exploring ways to retrieve a boolean type field from MongoDB using Angular Formly

I recently had the opportunity to set up a basic search feature, focusing on the "paymentStatus" field in an Invoice document stored in a MongoDB (v3.4). This field is essentially a boolean value. When I trigger the search from an AngularJS 1.6 Formly inpu ...

Establishing a Connection between an Android Application and a Jersey RESTful Web Service

I have successfully created a basic REST Web Service that receives three Strings from a client and stores them in a database. It's currently functioning well when accessed from a Java client application. Now, I'm interested in replicating this f ...

angular-cli: Select templates based on the current environment

Currently, I am utilizing @angular/cli: 1.0.0 and aiming to utilize component templates based on the environment. The code implementation is as follows: import {Component} from '@angular/core'; import {environment} from '../environments/env ...

Multiple instances of the identical 'Angular application' displayed simultaneously on the webpage

We've created a unique Angular 1.0 application that we aim to embed as a 'widget' within another website built with classic asp.net. During the development phase of our angular app, we take advantage of a range of gulp tools for tasks such ...

Alter text within a string situated between two distinct characters

I have the following sentence with embedded links that I want to format: text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] m ...

Ways to retrieve a value from a span using the Document Object Model

sample.html <span id='char'>{{value}}</span> sample.ts console.log((<HTMLInputElement>document.getElementById('char'))) This code snippet will display <span id='char'>ThisIsTheValueupdated</sp ...

The function __WEBPACK_IMPORTED_MODULE_3_ionic_native__.a.open is returning an error

Is there a way to troubleshoot and resolve the following error: WEBPACK_IMPORTED_MODULE_3_ionic_native.a.open is not a function while utilizing the NishanthKabra/Ionic2_GoogleCalendar solution. I am interested in integrating Google Calendar into my Io ...

Mastering the use of Chrome in Selenium with the finesse of Protractor

As part of my automation framework, I attempted to use the Chrome browser. While I am able to trigger the browser by using the following code snippet: System.setProperty("webdriver.chrome.driver", "C:\\Users\prabhu\\chromedriver.e ...

Using the spread operator in React to distribute JSX elements within a map function

I am struggling with mapping over an array within another array to create a Picker and am having difficulty returning JSX elements instead of an array of JSX elements. Here is the code example: {modelA.map((mA) => { const pickerItems = mA.modelB.m ...

Is there a way to implement hover behavior for a Material-UI Button within a ButtonGroup component?

When using MUI v5, I am encountering an issue where the first button in the code provided is only half working. The button is initially colored red (both the border and text), however, upon hovering over it, the color of the border changes to blue. This is ...

"Encountering a problem when trying to display Swagger-Editor for the second

While integrating the swagger-editor package into my React application, I encountered an issue. The first time I fetch the Swagger specifications from GitHub, everything works perfectly and validates correctly. However, upon rendering it a second time, an ...