Exploring the World of JSON Mapping Libraries

In my project, I am dealing with objects (like a ball) that have specific data members and functions. These objects are being retrieved from various servers, each with its own hierarchy. For example:

class Ball {
  int size;
  string color;
}

An instance of this class in JSON would look like this:

{ ball: {
size: 3,
color: red
}}

The challenge arises when I encounter a different hierarchy for the same type of object. For instance, another server may provide a Boll object with these attributes:

Class Boll{
int mass;
View color;
}

Class View {
string color;
}

This results in a JSON object like:

{ Boll: {
mass: 3,
view: {
 color: red
}}

Despite the varying hierarchies, it is clear that these classes share similarities.

I initially attempted to create a Map<string, string> where I could match up attributes between the two classes. However, as the objects became more complex (e.g., with nested objects like "view"), my solution became insufficient. With the complexity of objects in my project, I need a new approach to effectively handle these diverse object structures.

Answer №1

To streamline your Angular code, consider defining a single Ball object:

class Ball {
mass: number;
color: string;
}

For each request, you can easily map the service data to your object based on the known format:

public fetchBallsFromServerA(): Observable<Ball[]> {
 return this.http.get('ballUrlA')
   .map(response => { 
     let balls: Ball[] = response.json()
         .map(val => { 
             return { mass: val.size, color: val.view.color};
          });
      return balls;
   })

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

What is the best way to navigate through multiple layers of nested JSON elements in C#?

Received a JSON response from a public API with a specific structure as shown below. [ { "ID": "12345", "company": [ { "contract_ID": "abc5678", "company": [ { &quo ...

Retrieving decimal value from a given string

Currently, I am working with Google Maps and encountering an issue with distance values being returned as strings like 1,230.6 km. My goal is to extract the floating number 1230.6 from this string. Below is my attempted solution: var t = '1,234.04 km ...

I have a dynamic blog site that is generated on the fly using Ajax, making the content unsearchable

I have a blog website that is created dynamically using Ajax (XMLHttpRequest) and the HTML History API. One issue I am facing is that my content is not searchable by search engines like Googlebot. I know that Google is now able to analyze such sites, but w ...

Retrieving both keys and values from a JSON String with BasicDBObject when working with a list

My String holds a JSON data with a list structure as shown below: { "counts":[ {"foo827138": 123124, "bar2918":312312, "something_else321-313":2321321}, {"foo1231412": 4321, "bar1231515":123, "something_else3012931":7282}, {"fo ...

JavaScript Array Problem

Could you please review the code below and help me understand why I am encountering issues when trying to run the program? $(document).ready(function() { var comp = new Array("AAPL", "MSFT", "XRTX&"); var t = setInterval(function(){ ...

Translating from a higher-level programming language to a lower-level programming language

Is compilation effectively the transformation of high-level programming languages (HLL) into machine code or low-level language? If so, why is TypeScript (a HLL) compiled to JavaScript (also a HLL) instead of being compiled to a low-level language? ...

PHP JSON array conversion

[ { "id":"26", "latitude":"10.308749502342007", "longitude":"123.88429984649656" }, { "id":"28", "latitude":"10.313816172726275", "longitude":"123.89030799468992" } ] I have retrieved this JS ...

Encountering issues in parsing JSON for PhoneGap Application

I've been struggling with parsing JSON data for a unique PhoneGap application that is dynamically generated by a localStorage variable. The PHP script is functioning properly, but the JavaScript code seems to be encountering issues when trying to pars ...

Excessive memory consumption during JSON parsing

I'm currently parsing JSON data and saving it into an array. However, as soon as the parsing begins, memory usage goes from around 25mb to 800mb. I tried adding an @autoreleasepool in the GCD block after some advice, but it didn't help. Here&apo ...

Does JSX/TSX markup act as a constant that is passed by value or by reference?

In a separate file called EmptyNode.tsx, I have defined a constant: export const EmptyNode = <></> This constant is used to return an empty node when there is no content to display. For example: ... render() { if(!this.props.data) { ...

Issue with retrieving JSON data in chart object: Error reading property 'length' of undefined in Angular/ng2-charts

     I have successfully retrieved JSON data in the following format:    [2193,3635,8417,0] The data is coming from localhost:8080. I aim to utilize this dataset for displaying a pie chart. Below is the code snippet from one.html: <div> ...

Spring framework encounters an error when trying to deserialize a JSON instance

I'm facing an issue while trying to send a JSON long list and retrieve records from the database. Here is my controller: @Api(tags = Endpoint.RESOURCE_customer, description = "customer Resource") @RestController @RequestMapping(produces = MediaType. ...

Components unable to exchange data using Service

Trying to pass values from one component to another, but encountering issues with the code. The values are showing as undefined on the next page. Below is the code for my service class named UtilityService.ts: import { Injectable } from '@angular/co ...

What is the process to save all decoded information into a JSON file?

I am encountering an issue while trying to convert XML data into a JSON file. The problem arises when I attempt to write the marshaled data to the JSON file - it seems to only overwrite the existing data in the file, resulting in only the last XML element ...

Module Not Found Error: Electron and Typescript Collaboration

I am currently facing an issue while attempting to build my electron application using typescript generated from the electron-quick-start-typescript project. I have included an additional module named auth.ts, but unfortunately, it is not being recognized ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...

Populate form input fields of an iframe in Angular 4 with predefined values

Currently, I am incorporating an iframe with a different domain into my Angular 4 application. I am looking to dynamically populate the input fields within the iframe's form. Is there a potential solution for this task? Appreciate any help or guidanc ...

Activate the datepicker in Angular by clicking on the input field

This is my html file: <mat-form-field> <input matInput [matDatepicker]="picker" placeholder="Choose a date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-date ...

Create object keys without relying on any ORM or database management systems like mongoose or mongodb

Exploring a Mongoose Object: recipe = { "ingredients": [ { "_id": "5fc8b729c47c6f38b472078a", "ingredient": { "unit": "ml", "name" ...

Issue: The use of destructuring props is required by eslint, and I'm currently working with a combination of react and types

I typically work with React in JavaScript, and I recently encountered an error message stating "Must use destructuring props at line 14" while trying to define a button for use in a form. Here is the code snippet in question: import React from 'react& ...