Tips on formatting JSON objects that contain fields with their own object types?

UPDATE: I've tried something similar to this, but it's not working. I believe there lies the issue

var stringifyObj = JSON.stringify({
      "addressAddressId":$('#address').val(){ 
          "cityId:"$('#city').val(){
                "postalCode":$('#postalCode').val() 
           } 
      }
});     

*When I create a test client in Netbeans, the JSON structure (GET/JSON) looks like this. How can I implement this using JavaScript and the Stringify function? *

    "addressAddressId": {
        "addressId": 1,
        "address": "Railway Street 2",
        "address2": null,
        "district": null,
        "postalCode": "20360",
        "phone": null,
        "coordinates": null,
        "latitude": null,
        "longitude": null,
        "directions": null,
        "description": null,
        "addrZipCityCountry": null,
        "lastUpdated": 1361754860000,
        "cityId": {
            "cityId": 1,
            "city": "",
            "lastUpdate": 1361754850000,
            "countryCountryId": {
                "countryId": 1,
                "country": "Sweden",
                "lastUpdate": 1361754837000
            }
        }
    },

INQUIRY

  1. What is the correct syntax for using JSON.stringify with custom object types such as City-object within Address-object?
  2. Do I need to include every field in the JSON if I'm not using @JsonIgnoreProperties({""})? I only require address, city, and postal code. Address is of type Address with a string address field on the server side, while City is of type City containing a string field for city name, etc.

Answer №1

Uncertain of your intentions with the Javascript function provided above, but if you aim to generate JSON in a similar structure using Javascript, consider this approach :

var stringifyObj = JSON.stringify({
  "addressAddressId": {
    "addressId": 1,
    "address": "Järnvägen 2",
    "address2": null,
    "district": null,
    "postalCode": "20360",
    "phone": null,
    "coordinates": null,
    "latitude": null,
    "longitude": null,
    "directions": null,
    "description": null,
    "addrZipCityCountry": null,
    "lastUpdated": 1361754860000,
    "cityId": {
        "cityId": 1,
        "city": "",
        "lastUpdate": 1361754850000,
        "countryCountryId": {
            "countryId": 1,
            "country": "Sweden",
            "lastUpdate": 1361754837000
        }
    }
  }         
}); 

The essential step is enclosing the JSON string as a parameter for JSON.stringify.

If constructing the object gradually is needed, rather than supplying all properties at once as shown above, consider this alternative :

var obj = {};
//add properties as required
//basic properties
obj.addressId = 1;
obj.address = "Järnvägen 2";
obj.address2 = null;
//nested properties
obj.cityId = {};
obj.cityId.cityId = 1;
obj.cityId.countryCountryId = {};
obj.cityId.countryCountryId.countryId = 1;

Once all object properties are filled appropriately, utilize JSON.stringify like so :

var stringifyObj = JSON.stringify(obj);

To achieve the JSON format depicted in your example, further encompass the obj variable like this :

var stringifyObj = JSON.stringify({ addressAddressId = obj });

Hoping the concept is clear :)

Answer №2

There appears to be a missing comma at this point, however, it may not necessarily be the cause of the issue.

"postalCode": {
    "postalCode": $('#postalCode').val()
} <--- a comma is required at this location

"addressAddressId": {

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

Tips for Sending a Message Using TypeScript Websockets

I'm currently working on an Angular application that requires subscribing to a websocket to receive incoming data. Within the Angular service, I have the following code snippet: setContextChannel(channel) { this.contextWS = new WebSocket(channel ...

Looking for a method to dynamically assign a class to a particular div depending on the href attribute of an anchor tag?

On a website equipped with jquery and jquery ui, the following information could come in handy. The goal is to have multiple modal windows on the site that can be accessed through different anchor tags. For example, there is a modal window named modalone ...

Sequelize doesn't delay for the function's return value

When working with Sequelize and implementing a where condition, I need to utilize a function that will provide an array like [118, 116, 125]. Here is the code snippet: function getQuestionForQuickPreparation(req, res){ let user_id = req.params.id; async ...

Numerous Fascinating Challenges with React Native

Looking to share my React Native project and seeking help with some issues I'm facing. Despite multiple attempts, I have been unsuccessful in resolving them. Can anyone provide assistance? I have thoroughly searched Stack Overflow for similar questio ...

Learning to access JSON data stored in local storage and presenting it in a VUE component

I'm having trouble displaying the content of a json file (books.json) as a list on my website using VUE. Here is the code I'm currently working with: <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> & ...

Ways to retrieve a data element from an XML document?

In the line below, a JSON result is returned json['@Microsoft.Dynamics.CRM.fetchxmlpagingcookie'] The output is displayed as a string '<cookie pagenumber="2" pagingcookie="%2520page%253d%25221" istracking="False& ...

Issue with function execution within useEffect() not being triggered

I am facing an issue where two functions in my component are not being called every time it renders, despite my efforts. Placing these functions in the dependency array causes an infinite loop. Can anyone identify why they are not executing? function Por ...

Can the values of an enum in TypeScript be altered dynamically?

Can the values of an enum be dynamically changed? I currently have an enum set up like this enum MyEnum{ Error = "Error", Warn = "Warnings" } I have realized that in order for the values like Error and Warnings to be translated int ...

Tips for adjusting image hues in Internet Explorer?

I have successfully altered the colors of PNG images in Chrome and Firefox using CSS3. Here is my code: #second_image{ -webkit-filter: hue-rotate(59deg); filter: hue-rotate(59deg); } <img src='http://i.im ...

InvalidAction: The function forEach cannot be applied to "res"

Here is the HTML code that I am currently working with: <div *ngIf="chart" class="col-xl-4 col-lg-6"> <div class="card cardColor mb-3"> <div class="card-header headColor"> <img class="img-fluid" src="../../../ ...

Create a generic function that retrieves a specific property from an array of objects using the select method

Currently, I have implemented four functions that select entries from an array based on different properties. if ($scope.filters.filter1) $scope.filteredEntries = $scope.filteredEntries.filter(function (o) { return o.field1 === $scope.filt ...

Is there a way to delete added information using a trigger that has been inserted through ajax?

I created a function in jQuery and Ajax to add information from a separate PHP file to another file. Let's name the destination file "Homepage" and the file with the data "Template". Here is the function I used: var box = $('#infoPageContainer& ...

The v-on:click event handler is not functioning as expected in Vue.js

I am currently learning vue.js and facing some challenges. Below is the code snippet from my HTML page: <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net ...

inquiries regarding WCF REST service utilizing WebClient

I'm feeling a bit lost when it comes to understanding wcf rest. When calling a login method, should I use POST or GET? After setting up a POST request, I came across articles stating that POST should be used for updating data and GET for retrieving ...

The data type 'number' cannot be directly converted to the data type 'string'. What is the best way to cast a number as a string?

How can I convert a number to a string in a typescript file within Angular 7? I need to send two pieces of data, an ID and a name, to the backend. However, the backend only accepts the name. What steps should I take to correct this issue? public saveCode ...

What sets apart $.replaceWith() from the combination of $.remove and $.appendTo()?

I have noticed that when using these two pieces of code, I get different outcomes. In theory, they should yield the same result. What exactly sets them apart? var mapString = '<map id="map"><area shape="poly" coords="52,21,92,21,92,196,52,19 ...

Sending JSON data from a form submission using jQuery

CSS <div id="content" class="main"> <h1>Welcome to Unique Exchange</h1> <p>Join us by filling out the form below:</p> <form id="signupForm"> <ul> <li><input type="text" id= ...

jQuery disregards the else-if statement

Currently, I am developing a web application that prompts the user to input an "application" by providing the StudentID and JobID. With the help of jQuery, I am able to notify the user if the student or job entered does not exist, if the application is alr ...

Efforts to avoid repeated entries are proving ineffective

Currently, I am fetching information from an API in the form of an array of objects. Following this, I need to cross-reference this data with entries in a database to identify any duplicates based on the URL field. However, during the process of insertin ...

Transforming a string return method into JSON using REST apis

When I call a Spring method in my controller that returns a String, and consume the web service using Angular's $http module, I receive the following error: SyntaxError: Unexpected token a at Object.parse (native) This is the code snippet from my c ...