Submitting a nested JSON body in ASP MVC

I'm currently struggling to send a nested JSON body to an API, and I've tried a few different approaches without success. The JSON values are sourced from multiple models, making it quite complex for me to handle. Any assistance or guidance on this matter would be greatly appreciated.

public Object getfreight()
    {
         var json = "{" +
"'from': {" +
    "'postcode': '3207'" +
"}," +
"'to': {" +
    "'postcode': '2001'" +
"}," +
"'items': [" +
    "{" +
        "'length': 5," +
        "'height': 5," +
        "'width': 5," +
        "'weight': 5," +
        "'item_reference' : 'abc xyz'," +
        "'features':{" +
            "'TRANSIT_COVER': {" +
                "'attributes': {" +
                    "'cover_amount':1000" +
                "}" +
            "}" +
        "}" +
    "}" +
"]" +
"}";

 string url = 
"https://digitalapi.auspost.com.au/postage/parcel/domestic/calculate.json?length=22&to_postcode=3083&from_postcode=3076&weight=2&height=40&width=50&service_code=AUS_PARCEL_REGULAR";


         //synchronous client.
        var client = new WebClient();
        var serializer = new JavaScriptSerializer();
        client.Credentials = new NetworkCredential("***", "***"); 

        client.Headers.Add("Content-Type: application/json");
        client.Headers.Add("Accept: application/json");
        client.Headers.Add("account-number: ***");
        var data = serializer.Serialize(json);
        var content = client.UploadString(url,json);

        var jsonContent = serializer.Deserialize<Object>(content);
        return jsonContent;
    }

Answer №1

Having trouble using jQuery to send your json object to the API?

 function Search () {
       try {
                    var req = {
                        length:"5",
                        Higet: "10",
                        item_reference: "",  
                    }

                    $.ajax({
                        url: https://digitalapi.auspost.com.au/postage/parcel/domestic,
                        type: 'POST',
                        data: req,
                        dataType: "json",
                        async: true,
                        success: function (result) { 


                        },
                        error: function (e) {

                        }
                    });
                }
                catch (e) {

                }
            }

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

streamlining form updates in vue

The code snippet provided is functional but unnecessarily complicated and lengthy. I am seeking a more efficient approach to achieve the desired outcome. <h6><label for="number">Change Number</label></h6> ...

How can I incorporate a CDN link into the newly updated Next.js App Router?

Exploring next.js has been quite an adventure for me, and I'm impressed with its capabilities. However, being a beginner, I have encountered some challenges. One issue I am currently facing is the difficulty in using Google icons without a CDN link in ...

Avoid filling the container with an excessive amount of grids while maintaining the correct aspect ratio

I encountered a situation where I needed to dynamically create a grid with square grids of dimensions MxN. Below is the code snippet for achieving this: rerender = (event) => { const height = document.getElementById("y-input").value; const width ...

When presented with a JSON string, transform the nested JSON structure into key value pairs. The key for each pair will be the name of the element hierarchy combined with an underscore

When presented with a json string, the task is to convert the nested json into key value pairs. Each key in the pairs should consist of the name of the element hierarchy followed by an underscore. { "person": { "id": 1, &quo ...

Explain the concept of render hijacking in react technology

After learning about High Order Components (HOC), I came across the concept of render hijacking. Can someone please explain what exactly render hijacking entails? ...

What causes the AJAX JSON script to output an additional 0?

Within my WordPress website, there is an AJAX function that reaches out to a PHP function in order to retrieve a specific value from a transient record stored in the Database. Whenever I trigger this function with jQuery, I successfully receive the result ...

Why is it that a website is loading at a snail's pace on Angular?

Working on my college project has been going smoothly, except for one issue with slow loading times. It's frustrating how long it takes to load. I suspect that there might be an error in the deployment process or something else causing the delay. The ...

Error has occurred: Unable to assign a value to an undefined property using axios

Within my Vue.js component, I am utilizing axios to fetch a JSON array consisting of `joke` objects: <template> <div id="show-jokes-all"> <h2>Showing all jokes</h2> <div v-for="joke in jokes"> ...

Discover the trick to capturing the back button and dynamically refreshing the webpage with ajax!

I am currently facing an issue with a dynamically updating web page where I need the browser's "back" button to trigger a function for refreshing data instead of navigating back a page. I have managed to trap the "back" button using the following code ...

Save the JSON data into a variable inside a React utility component

Currently, I am new to React and facing an issue with fetching data and storing it in a variable. I have been struggling to understand why my SetMovieResponse function is not working as expected. I have tried stringifying the JSON before sending it, but w ...

Implementing a file size restriction in C# when writing a lengthy JSON string using the System.IO.Stream

I have a large array stored in Json format, and the result is saved in a variable called "sz" (string). However, when I attempt to save this Json result (string sz) to a file, it seems that not all of the string gets saved. Why is this happening? The siz ...

Should we consider declaring a string field as JSON in a gRPC proto file?

When working with protobuf, it can be challenging to define a flexible structure in certain scenarios. For example: message Foo { int a = 1; repeated int a_other = 2; } In some cases, we may not want the service's client to pass both the a and ...

Deactivate background hover effects for bar charts in Recharts

Is there a way to disable the gray background that appears when hovering over bar charts in Recharts? I'm using version 1.4.1 and my code looks like this: import React from "react" // Recharts import { Bar, BarChart, CartesianGrid, ResponsiveContain ...

Ignored appSettings in the Selenium test class library's app.config file

I am currently running tests on an ASP.Net MVC web application using selenium. I want to utilize the app settings in the app.config file of the test project, rather than the ones in the web.config file of the actual web application. However, it seems that ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Methods for transferring data to controller in Angular Modal service

After implementing the angular modal service discussed in this article: app.service('modalService', ['$modal', function ($modal) { var modalDefaults = { backdrop: true, keyboard: true, m ...

Tips for incorporating a User ID object into an Ajax request

Currently, I am delving into the world of web development and tackling a client-server project that involves allowing users to authenticate themselves and store their blood pressure readings. While the authentication part is functioning properly, I am enco ...

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'</p> I have been ...

React State Update Triggered by Changing Hidden Input/Textarea Value - No User Input Required

To activate a function when the contents of a hidden input, textarea, or textfield change in React without requiring user input to trigger it, you will need to dynamically adjust the value of the hidden input and then have the function automatically exec ...

Retrieving a value from an array of JSON objects using Ruby

I am working with an array of JSON objects called line: [{"label":"Name","value":"Bob","identifier":"field2","type":"oneLineText","page":1,"page_name":"Step 1","width":"100%"},{"label":"Email","value":"<a href="/cdn-cgi/l/email-protection" class="__cf_ ...