Converting Jackson output to JSON in Angular

The server I'm currently working with made a change to the REST format, transitioning from plain JSON:

    {           
        "removedVertices": [
            {
                "id": "1",
                "info": {
                    "host": "myhost",
                    "port": "1111"
                },
                "name": "Roy",
                "type": "Worker"
            }
        ],
        "id": "2",
        "time": 1481183401573
    }

To a Jackson formatted version:

    {
          "removedVertices": [
          "java.util.ArrayList",
           [
                   {
                         "id": "1",
                          "info": [
                                "java.util.HashMap",
                                {
                                    "host": "myhost",
                                    "port": "1111"
                                }
                         ]
                         "name": "Roy",
                         "type": "Worker",                             
                    }                       
            ]
            "id": "2",
            "time": 1482392323858
    }

What is the best way to parse this data back to its original format using Angular/Javascript?

Answer №1

To specifically handle array manipulation, my approach would involve leveraging the capabilities of underscore.js library by crafting a recursive function tailored to eliminate the Jackson type.

function convertJacksonToJson(input) {
  return _.mapObject(input, function(value, key) {
    if (_.isArray(value) && value.length > 1) {
      // Remove the Jackson type and retain the second element in the array
      return value[1];   
    }
    else if (_.isObject(value)) {
      // Recursively apply the transformation
      return convertJacksonToJson(value);
    }
    else {
      // Preserve the original value (e.g. primitive types)
      return value;
    }
  });
} 

Answer №2

In order for an API to be considered truly restful, the server must not return anything other than plain JSON results. It seems like there may be a problem on the server side that needs to be addressed.

It is possible that the server has enabled the Polymorphic Type Handling feature, causing this issue. To learn more about this feature, you can visit this link and here.

To resolve the issue and receive plain JSON results, it is recommended to disable the Polymorphic Type Handling feature.

Answer №3

One notable distinction that stands out to me is the inclusion of an extra string element at index 0 in arrays.

If you consistently encounter this specific structure, you can implement a solution like this:

function convertJacksonToJson(jackson) {
    jackson.removedVertices.splice(0, 1);

    jackson.removedVertices.forEach((rmVert) => {
      rmVert.info.splice(0, 1);
    });

    return jackson;
}

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

Error: Undefined state in a React class component has not been defined

I seem to be facing an issue with my code and I could use some assistance! When running npm install, I encounter an error if I use it with a file generated from create-react-app. It works perfectly fine in that scenario. However, I am unsure about the miss ...

Three.js emits a selection list

I'm currently working on creating a picking ray to determine if my 3D body in three.js has been clicked. I've tried following some advice from different sources like this post and this thread. This is the code I have so far: function checkClick ...

What is the best way to navigate through a complex array in React that includes objects and nested arrays?

I have been working on a JavaScript array that includes subobjects with arrays nested in them. My goal is to iterate through the entire parent object using React. Although I attempted the following approach, unfortunately it did not yield the desired outco ...

Is there a way for me to include .js or .cpp prior to using the Vim shortcut key gf?

When using a programming language like nodejs, the require function does not require the addition of the .js extension. For example: var Assert = require('./app_base'); However, in vim, when using gf, it cannot find app_base without the .js ext ...

Issue with table sorting functionality following relocation of code across pages

I had a working code that I was transferring from one webpage to another along with the CSS and JS files, but now it's not functioning properly. <head> <link type="text/css" rel="stylesheet" href="{{ STATIC_URL }}assets/css/style.css"> ...

Issue: ENOENT - The file or directory does not exist. uv_chdir encountered an error when attempting to create a directory and navigate into it

I am facing a challenge while developing a small application that installs files and modules in a new folder. The error I keep encountering is: { Error: ENOENT: no such file or directory, uv_chdir at process.chdir (/home/aboardwithabag/LaunchProject/n ...

Get rid of the delay when using ng-change

I am currently facing a challenge with two select boxes. Specifically, I need to hide the "Canada" selection in one box when it is selected in the other box. To address this issue, I have successfully implemented a solution on JSFiddle: https://jsfiddle.n ...

Tips on preventing the initial undefined subscription in JavaScript when using RxJS

I am having trouble subscribing to an object that I receive from the server. The code initially returns nothing. Here is the subscription code: ngOnInit() { this.dataService.getEvents() .subscribe( (events) => { this.events = events; ...

Limit the y-axis on CanvasJS visualization

Is it possible to adjust the minimum and maximum values on the y-axis of the graph below: new CanvasJS.Chart(this.chartDivId, { zoomEnabled: true, //Interactive viewing: false for better performance animatio ...

The JSON response body contains an escaped string

Currently, I am in the process of developing an API using C#.NET. The API is responsible for processing data, which is then returned in the form of a JSON string (not a JSON object). However, upon testing the API using Postman, the response body displays t ...

What is the best way to initiate an image loop with the click of a button?

<p align="center"> <button onclick="slideit()">Run the loop</button> <!-- Start Weather Image Loop --> <img src="firstcar2.gif" name="slide" width="900" height="500" /> <script type="text/javascript"> <!-- var ...

Dealing with a passed EJS variable in string form

When working with passed data in ejs, I usually handle it like this and it works perfectly: let parsed_json = JSON.parse('<%-JSON.stringify(passed_data)%>'); However, I encountered a problem when trying to dynamically pass a string variabl ...

Components are mysteriously sharing props with each other

In my Vue component, I am encountering an issue when passing two different arrays to separate instances of the same component and then using v-for to send a single item from each array to another component via props. The problem arises when I inspect the p ...

Angular: Exploring the differences between $rootScope variable and event handling

I have a dilemma with an app that handles user logins. As is common in many apps, I need to alter the header once the user logs in. The main file (index.html) utilizes ng-include to incorporate the header.html I've come across two potential solution ...

Angular RxJS: Trigger an action upon subscribing to or unsubscribing from an observable

I'm in the process of converting some Javascript events into Observables using RxJS within an Angular application built on the Ionic framework. My goal is to begin listening for events when the "client" invokes .subscribe(), and then stop listening wh ...

Instructions on establishing a connection with a MongoDB server using JavaScript

Hello all, I am a complete beginner when it comes to working with mongodb and java script. I am currently trying to figure out how to establish a connection to my local mongodb instance using java script so I can retrieve a list of documents. Does anyone ...

Tips on crafting tailored CSS styling for targeted div elements such as before and after:

Looking to style specific div elements with the same class name? <div class="main"> <div class="banner_image"> banner 1</div> <div class="banner_image ">banner 2</div> <div class="banner_image ">banner 3</di ...

Experiencing difficulties when trying to connect a subdirectory in Angular and encountering an error

My Angular site has a page with a link that leads to #admin/editCourse. <li><a href="#admin/editCourse" data-toggle="tab">Edit Course Info</a></li> However, when I click the link, Javascript (JQuery) throws an error: Syntax erro ...

What is the method for showcasing a particular phrase you are seeking from a string within POSTGRESQL?

Displaying a sample row value CREATION_DATE: 2021-08-30 USER_EMAIL: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="751f14161e350614180519105b161a18">[email protected]</a> ACTION: 'FileAccessedExtended&a ...

The error `Error occurred when rendering: Users' data cannot be mapped` indicates a problem with the rendering process

Utilizing useSWR for data retrieval from an endpoint and attempting to display all returned data, I encounter the following error: unCaught (in promise) fetchedUsers.map is not a function uncaught TypeError: fetchedUsers.map is not a function The provided ...