The JSON data appears to be correct, yet it is not functioning properly when transmitted to X

I have a JSON object that has been validated using https://jsonlint.com/. However, I am encountering an error when trying to use this JSON with the Xero API as shown below.

{
  "Type": "ACCREC",
  "Status": "AUTHORISED",
  "DueDate": "2021-12-11T14:24:08Z",
  "InvoiceNumber": "PRO152125",
  "Contact": {
    "ContactID": "ddd-05f9-46dd-b4a6-2ccbb5deb330"
  },
  "LineItems": [
    "{\"Description\": \"test1\", \"Qty\": 0.30, \"UnitAmount\": 950.0, \"TaxType\": \"OUTPUT2\", \"AccountCode\": \"200\"},\n{\"Description\": \"test2\", \"Qty\": 0.30, \"UnitAmount\": 300.0, \"TaxType\": \"OUTPUT2\", \"AccountCode\": \"200\"}"
  ]
}

{
  "ErrorNumber": 14,
  "Type": "PostDataInvalidException",
  "Message": "JSON for post data was invalid,Error converting value \"{\"Description\": \"test1\", \"Qty\": 0.30, \"UnitAmount\": 950.0, \"TaxType\": \"OUTPUT2\", \"AccountCode\": \"200\"},\n{\"Description\": \"test2\", \"Qty\": 0.30, \"UnitAmount\": 300.0, \"TaxType\": \"OUTPUT2\", \"AccountCode\": \"200\"}\" to type 'Xero.API.Library.DataContracts.LineItem'. Path 'LineItems[0]', line 1, position 417."
}

Could someone assist me in understanding why this issue is occurring?

Answer №1

To deserialize your JSON to the class correctly, the API expects it in the following format:

class MyClass 
{ 
    ..properties

  List<LineItem> LineItems...
}

class LineItem
{
  ... properties inside of the string
}

Your JSON is technically valid but structured differently:

class MyClass 
{ 
    ..properties

  List<string> LineItems...
}

The API serializer cannot convert a List<string> to a List<LineItem>, which causes the error.

To resolve this issue, you can adjust the JSON as follows:

  var jsonObject=GetFixedJsonObject(json);
  
  var fixedJson=jsonObject.ToString();


public JObject GetFixedJsonObject(string json)
{
    var jsonObject = JObject.Parse(json);
    
    var jsonLineItems = "[" + (string)jsonObject["LineItems"][0] + "]";
    
    jsonObject["LineItems"] = JArray.Parse(jsonLineItems);
    
    return jsonObject;
}

After making these changes, your fixed JSON will look like this:

{
  "Type": "ACCREC",
  "Status": "AUTHORISED",
  "DueDate": "2021-12-11T14:24:08Z",
  "InvoiceNumber": "PRO152125",
  "Contact": {
    "ContactID": "ddd-05f9-46dd-b4a6-2ccbb5deb330"
  },
  "LineItems": [
    {
      "Description": "test1",
      "Qty": 0.3,
      "UnitAmount": 950.0,
      "TaxType": "OUTPUT2",
      "AccountCode": "200"
    },
    {
      "Description": "test2",
      "Qty": 0.3,
      "UnitAmount": 300.0,
      "TaxType": "OUTPUT2",
      "AccountCode": "200"
    }
  ]
}

Answer №2

Your line item is currently wrapped in quotes, making it appear as a single string. You can correct this by following the example below:

{
    "Type": "ACCREC",
    "Status": "AUTHORISED",
    "DueDate": "2021-12-11T14:24:08Z",
    "InvoiceNumber": "PRO152125",
    "Contact": {
        "ContactID": "ddd-05f9-46dd-b4a6-2ccbb5deb330"
    },
    "LineItems": [{
        "Description": "test1",
        "Qty": 0.30,
        "UnitAmount": 950.0,
        "TaxType": "OUTPUT2",
        "AccountCode": "200"
    }, {
        "Description": "test2",
        "Qty": 0.30,
        "UnitAmount": 300.0,
        "TaxType": "OUTPUT2",
        "AccountCode": "200"
    }]
}

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

Looking for the best JSON database library?

Currently utilizing Node.js... Personally, I find SQL to be unappealing. My preference lies with JSON, as I desire to store my server data in that format. While I can utilize JSON.parse and .stringify, it seems like a suboptimal approach for larger appli ...

Should reports be created in Angular or Node? Is it better to generate HTML on the client side or server side

I have a daunting task ahead of me - creating 18 intricate reports filled with vast amounts of data for both print and PDF formats. These reports, however, do not require any user interaction. Currently, my process involves the following: The index.html ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...

Is there a way to generate the specific JSON file format using my PHP script?

Here is the desired output: [ {"Airtel":{"v": 50.00}}, {"Hutch":{"v": 10.00}}, {"Idea":{"v": 10.00}}, {"TATA":{"v": 10.00}}, {"Vodafone":{"v": 20.00}}, {"Aircel":{"v": 15.00}} ] Since the data is retrieved from a MySQL database, it ...

Unexpected object returned by the spread operator

Currently, I am utilizing node and specifically using babel-node. "start": "nodemon --exec babel-node --presets es2015 index.js" However, I have encountered an issue with my spread syntax in the following code snippet: export const login = async (parent ...

What is the best way to retrieve a selected value from one dropdown list and populate it into another dropdown

Can someone assist me with retrieving the selected answer from one drop-down list and populating it into another drop-down list? Below is my code for programming groups A and B: Example: If a user selects an option from group A and group B, I would li ...

Next.js encountered an invalid src prop

Error: The src prop is invalid () on next/image, the hostname "scontent-atl3-2.xx.fbcd.net" has not been configured under images in your next.config.js For more information, visit: https://nextjs.org/docs/messages/next-image-unconfigured-host ...

Execute a function when the selected option changes

Now I have implemented a code that dynamically changes the foreign key based on user input and retrieves data accordingly. Here is how it all comes together: Starting with the HTML page: <div class="large-6 columns"> {% csrf_token %} <in ...

Retrieve the id and value attributes of a checkbox using the success callback function in jQuery AJAX

I'm currently working on a web application project using JSP, jQuery, AJAX, MySQL, and Servlet. Within my project, I have a table.jsp file structured as follows: <form id="frm_table"> Username : <input type="text" id="txt_name" name= ...

Attempting to create a Next.js 13 application, but struggling with using the client-side functionality

Exploring Next.js for the first time, I embarked on creating a simple application. Everything was going smoothly until I attempted to include a "use client" tag at the beginning of a component to utilize certain hooks. This resulted in the app breaking and ...

The XMLHttpRequest function successfully logs data in the console, but does not return the data within the function itself

I find it puzzling that the console.log statement at the end of the code snippet displays the data as expected, while the return optiondata line does not. function populate_selectbox() { var ajaxRequest; try { // Opera 8.0+, Firefox, S ...

Utilize moment.js to convert an epoch date into a designated time zone

I've spent countless hours searching for a resolution to the issue with moment.js and its inability to accurately display the correct date for a given local time zone. Let me explain my predicament: The flight API I'm utilizing provides me w ...

Tips for personalizing the datetime format of JSON before the web API transmits the response

Is there a way to customize the DateTime format returned by my webapi, as the default one is not suitable for my needs? ...

Creating a load more feature with Vue

Having some trouble implementing a load more button that adds 10 more items to the page when clicked. The button code seems to be causing issues as all items still appear on the page and there are no errors in the console either. As a result, the button is ...

Combining php with jquery

This message contains a successful integration of PHP code within jQuery using the AJAX method. However, there are errors encountered which may be due to my lack of experience in jQuery. Uncaught ReferenceError: save_customer is not defined Uncaught Synt ...

Media publications do not conform to the current trends

I'm currently utilizing the HTML-to-paper plugin to print my content on a printer. However, I've encountered an issue where it doesn't seem to apply any of the styles I've defined within @media print. The challenges I'm encounteri ...

Transmit intricate data structure to a web API endpoint using AJAX requests

When attempting to send a complex object named vm containing an object 'Budget' and an array 'BudgetDetails' populated with rows from an HTML table to my API controller using AJAX, I encounter the error message "Uncaught RangeError: Max ...

Ways to clear dropdown selection in Vue based on a specific condition?

I am currently developing a dropdown menu for selecting visit status options, which include "pending," "canceled," "rejected," and "approved." In the case of an approved visit status, I would like the dropdown selection to only display the options for "can ...

I encountered an error stating that "next is not a function." Interestingly, this code works perfectly fine with another source that was recommended by a friend

const express=require('express'); const app=express() //middleware const customMiddleware=(req,res,next)=>{ console.log('this is a custom middleware that will be executed before the route handler'); next(); } customMiddlewar ...

When using Mongoose paginate, there is always one missing document

I currently have a database with 6 documents and the following route: router.get('', async (req, res) => { const search = req.query.search !=null ? req.query.search : ""; const page = req.query.page !=null ? req.query.page : 1; const limit = ...