Converting JSON to TypeScript: How to properly serialize property names instead of the base class field names

Take a look at the code snippet below. I anticipate the serialized result to be:

{
    "origin": {
        "x": 1,
        "y": 2
    },
    "size": {
        "width": 3,
        "height": 4
    }
}

However, the actual result is:

{
    "origin": {
        "a": 1,
        "b": 2
    },
    "size": {
        "a": 3,
        "b": 4
    }
}

Is there a way to instruct json2typescript to use the property names in the Coord and Size classes instead of using the names from the common base class Pair?

I attempted to remove the @Json decorators from Pair, but then nothing is serialized in Coord and Size.

@JsonObject("Pair")
export class Pair2
{
    @JsonProperty("a", Number)
    protected a: number;
    @JsonProperty("b", Number)
    protected b: number;

    constructor(a?: number, b?: number)
    {
        this.a = a;
        this.b = b;
    }
}

@JsonObject("Coord")
export class Coord2 extends Pair2
{
    @JsonProperty("x", Number)
    public get x(): number { return this.a; }
    public set x(value: number) { this.a = value; }

    @JsonProperty("y", Number)
    public get y(): number { return this.b };
    public set y(value: number) { this.b = value };

    constructor(x?: number, y?: number)
    {
        super(x, y);
    }
}

@JsonObject("Size")
export class Size2 extends Pair2
{
    @JsonProperty("width", Number)
    public get width(): number { return this.a; }
    public set width(value: number) { this.a = value; }

    @JsonProperty("height", Number)
    public get height(): number { return this.b };
    public set height(value: number) { this.b = value };

    constructor(width?: number, height?: number)
    {
        super(width, height);
    }
}

@JsonObject("Rectangle")
export class Rectangle2
{
    @JsonProperty("origin", Coord2)
    origin: Coord2;
    @JsonProperty("size", Size2)
    size: Size2;

    constructor(origin: Coord2, size: Size2)
    {
        this.origin = origin;
        this.size = size;
    }
}

let jsonConvert: JsonConvert = new JsonConvert();
jsonConvert.operationMode = OperationMode.LOGGING; // print some debug data
jsonConvert.ignorePrimitiveChecks = false; // don't allow assigning number to string etc.
jsonConvert.valueCheckingMode = ValueCheckingMode.DISALLOW_NULL; // never allow null

let origin = new Coord2(1, 2);
let size = new Size2(3, 4);
let rectangle = new Rectangle2(origin, size);

let rectangleJsonObj = jsonConvert.serialize(rectangle);
console.log(rectangleJsonObj);
let rectangleStr = JSON.stringify(rectangleJsonObj);
console.log(rectangleStr);

Answer №1

This is how I resolved the issue:

  1. Instead of relying on the json2typescript library, I opted for JSON.stringify and JSON.parse methods
  2. By implementing the toJSON() function, I was able to create an object with width and height attributes:
private toJSON = () =>
{
    return {
        width: this.width,
        height: this.height
    }
}

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

Is there a more efficient method for providing hooks to children in React when using TypeScript?

My component structure looks something like this: Modal ModalTitle ModalBody FormElements MySelect MyTextField MyCheckbox DisplayInfo ModalActions I have a state variable called formVars, and a function named handleAction, ...

Inference in Typescript - Detecting unknown key in an object

I am struggling to implement type inference from a props object that is passed to a component and then used in a render function. While I can retrieve the keys of the object correctly, all types are being interpreted as unknown. I need some assistance in f ...

Iterate through the array and show the information using Angular

enter image description hereI am a beginner in Angular and I am looking to iterate through an array in Angular. The array contains the following elements: "ticketsdetectives":[10,11,12,13] My goal is to display this data similar to the following ...

Exploring Angular 2 with Visual Studio 2015 Update 1 in the context of Type Script Configuration

After spending the last week attempting to set up and launch a simple project, I am using the following configuration: Angular 2, Visual Studio 2015 update 1, TypeScript Configuration In the root of my project, I have a tsconfig.Json file with the follow ...

A guide to efficiently removing an element in Angular using TypeScript by considering certain properties

I need help removing an element from an array based on any property such as its key, name, or email. HTML <tr *ngFor="let person of persons;" (click)="remove(person.key)"> <td>{{person.key}}</td> <td>{{person.name}}</td> ...

Angular is having trouble showing an image sourced from OMDBAPI

Currently, I am delving into the world of AngularJS. For my project, I aim to showcase movie posters sourced from http://www.omdbapi.com. HTML <div ng-app="moviesBrowserApp"> <div ng-controller="moviesCtrl"> <strong> ...

Updating a JSON data structure after removing an item using AngularJS

As a newcomer to AngularJS, I have created a Service using Java and integrated it into Angular to handle the deletion of Contact objects. On my homepage in AngularJS, this is the code I have: <!--RESULTS--> <form> <table class="table table ...

"Stylish form field design with outlined borders that displays a subtle hover

I am attempting to modify the background color of a mat-form-field outlined when hovering with the mouse. .mat-form-field.mat-form-field-appearance-outline.mat-form-field-outline-thick { // HOVER EFFECT background-color: $dark-blue-200; } The above ...

Creating a consolidated bundle of JavaScript files with the webpack module bundler for Angular application

I am new to angularjs and facing performance issues in my project due to multiple dependencies in separate js files. I want to bundle all these files into a single file using webpack. Can someone guide me on how to achieve this with webpack? ...

Guide on sending MySQL query results as JSON data using Ajax

I'm having trouble figuring out how to pass the results of a MySQL query into an HTML page using AJAX and JSON. I have the following code in ajax2.php: $statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2") ...

Converting objects to arrays in Typescript: A step-by-step guide

Can anyone assist me in converting a string to a Typescript array? Any help would be greatly appreciated. Take a look at the following code snippet: private validateEmptyOption(): any { console.log("CHECKED") let isValid = true; this.currentF ...

Ways to set a default value for a union type parameter without encountering the error "could be instantiated with a different subtype of constraint"

After referring to my recent inquiry... Can a default value be specified for valueProp in this scenario? type ValueType = 'value' | 'defaultValue' type Props<T extends ValueType> = Record<T, string> ...

When HTMLElement focus is activated, it interrupts the flow of execution

(the code presented is in TypeScript and I'm working with Angular 5, but I don't think that's the issue, so prove me wrong!) I have a basic input field that triggers events in an Angular component. (EDIT: I've added the complete compo ...

Please ensure to close the dropdown menu once the function has been called

I'm encountering an issue with a dropdown menu. When I expand the dropdown menu, everything works as expected. However, is it possible to disable the first search button and the txtSearch input field (referring to the class "glyphicon glyphicon-search ...

Guide to accessing Angular app on a mobile device within the same network

I'm facing an issue with my Angular App when trying to access it on mobile within the same network. I've attempted running ng serve --host <my IP> or ng serve --host 0.0.0.0 and it works well. However, the problem arises because the applica ...

Utilize Angular 4 Router to intercept every router modification

I want to implement a Breadcrumb feature. More about Breadcrumbs on Wikipedia To achieve this, I am considering creating a Service to manage it. However, I need a way to monitor any router state changes automatically, without having to add an onActivate ...

Tips on how child component can detect when the object passed from parent component has been updated in Angular

In the child component, I am receiving an object from the parent component that looks like this: { attribute: 'aaaa', attribute2: [ { value }, { value }, { value }, ] } This object is passed to th ...

Distributing a library of components using Vite, Vue 3, and Typescript to npm

My current challenge involves publishing a Vue 3 component library with Vite, all written in Typescript. The issue I'm facing is that the type definitions are not being included in the package when imported into another project. Upon importing the co ...

What is the best way to create a JSON endpoint for a WordPress page that includes HTML markup?

I am looking to create a JSON endpoint for this WordPress page so that it can be integrated into other PHP applications using the same HTML markup. By sharing CSS and JS files, the styles of this page will mirror those of the original WordPress page. & ...

Retrieve a value from a JSON string when the parent object's name is not predetermined

I am facing a challenge with extracting the property value named "Mode" from a JSON string, without knowing the parent property name. Here is an example of the JSON structure: { "CommomData": { "DateTime": { "Year": 2019, "Month": 3, ...