Learn how to generate a DataTable in C# by parsing multiple nested JSON Objects efficiently

Whenever I receive dynamic JSON data, it could be a JSON array, a simple JSON object, or nested JSON objects.

I am attempting to deserialize and convert the JSON object/array into a DataTable for further processing using Newtonsoft.Json.

Here is my current code:

public DataTable ConvertJson2DataTable(string jdata)
    {
        DataTable dt = null;

        try {
            dt = (DataTable)JsonConvert.DeserializeObject(jdata, typeof(DataTable));
        }
        catch (Exception ex)
        {
            MessageBox.Show("exception: " +ex.Message.ToString());

        }

        return dt;
    }

It works well for regular JSON objects and arrays. However, when dealing with complex JSON objects, I encounter an error message stating "Additional text found in JSON string after finishing deserializing object."

Below is a sample of the JSON data causing the issue:

{
  "ads": {
    "items": [],
    "total": 0,
    "page": 1
  },
  "member": {
    "memberId": "649991",
    "displayName": "",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066e6775677e7e7e466e6972696263676a2865696b">[email protected]</a>",
    "memberStatus": "Y",
    "smiId": "7aa205ea-7aa2-7aa2-7aa2-7aa205eac183",
    "facebookId": "100001412016857",
    "registerDate": null,
    "emailConfirmed": false,
    "smsConfirmed": false,
    "facebookConfirmed": false,
    "lineId": null,
    "wechatId": null,
    "displayImage": "",
    "firstName": "Hasadin",
    "lastName": "Pankran",
    "telephone": "",
    "mobile": null,
    "listingCount": {
      "online": 0,
      "edit": 0,
      "waiting": 0
    },
    "phones": null
  }
}    

Answer №1

To better represent a complex data structure or relational model, it is recommended to convert a table/datatable into a dataset instead of using datatable.

When converting JSON structure into a dataset, it should follow the format below:

{
    "ads": [{ 
         "total": 0, 
         "page": 1 
          }], 
    "member": [{
        "memberId": "649991",
        "displayName": "",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfb7beacbea7a7a79fb7b0abb0bbbabeb3f1bcb0b2">[email protected]</a>",
        "memberStatus": "Y",
        "smiId": "7aa205ea-7aa2-7aa2-7aa2-7aa205eac183",
        "facebookId": "100001412016857",
        "registerDate": null,
        "emailConfirmed": false,
        "smsConfirmed": false,
        "facebookConfirmed": false,
        "lineId": null,
        "wechatId": null,
        "displayImage": "",
        "firstName": "Hasadin",
        "lastName": "Pankran",
        "telephone": "",
        "mobile": null 
        }] 
}

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

Ways to retrieve the responseText within the jqxhr.complete callback function

Apologies in advance for my lack of knowledge in JavaScript and jQuery, this question may seem basic. I've searched through the jQuery documentation and Google but couldn't find an answer. I am attempting to trigger an action on the response onc ...

Verify whether the chosen options from a dropdown list coincide with a predetermined value

I am working with a form that generates dropdown lists dynamically. <c:forEach var="companyList" items="${company.detailList}" varStatus="status"> <tr> <td>c:out value="${companyList.employeeName}" /></td> <td> <select ...

Can you explain the inner workings of the provided code in a step-by-step manner?

I stumbled upon this code snippet that checks if the number of occurrences of an element in an array is greater than a specified value, and if so, it will remove the number: function deleteNth(arr,x) { var cache = {}; return arr.filter(function(n) { ...

Vue: Utilizing computed properties to monitor changes in offsetHeight of elements

I am working on a component that requires an array of 50 objects to be passed as a prop. <template> <div v-for="(item,index) in items" ref="items" :key="index"gt; // </div> </template> props: ...

Steps to avoid the button being submitted twice

I am facing an issue with two buttons in my code. One button is used to increase a count and the other button is meant to submit the count and move to the next page. The problem is that when I click on the "Proceed" button, it requires two clicks to procee ...

Gather and consolidate all files into a single file using Node.js / JavaScript

I currently have 3 JSON files located in my project/Folder file1.json { "id":"01", "name":"abc", "subject":[ "subject1":"Maths", "subject2":"Science" ...

The page switch with a jittery effect

Could really use some assistance with this code that has been giving me trouble for quite a while now. It's a simple HTML, CSS, and JS code involving two pages. [The second page overlaps the first by default, but adjusting the z-index of the first p ...

Split a string using two different delimiters to generate a multidimensional array

I have a string with specific data elements: 01;Tommy;32;Coder&&02;Annie;20;Seller I am looking to format it into an array like this: array (size=2) 0 => array (size=4) 0 => string '01' (length=2) 1 => string 'To ...

Is there a way to close the menu in react by clicking anywhere on the

Presently, I have a solution to close my topbar menu that involves clicking the menu icon. However, this method is not satisfactory because it only closes the menu when the icon is clicked. I am looking for a way to make the menu close when any area of th ...

Arranging arrangements in javascript

I am dealing with objects that contain the fields id and position. const items = [{id: 11, position: 1}, {id: 12, position: 2}, {id: 13, position: 3}, {id: 14, position: 4}, {id: 15, position: 5}, {id: 16, position: 6}]; These objects represent folders st ...

A guide to creating an HTTPS request using node.js

I am currently in the process of developing a web crawler. Previously, I utilized the following code for HTTP requests: var http=require('http'); var options={ host:'http://www.example.com', path:'/foo/example' }; ...

The Android application encountered an issue where the org.json.simple.JSONObject could not be converted to org.json.JSONObject

My task is to sort scores from a JSONArray and display only the top 10. Below is the code I have written. try { JSONArray jArray = new JSONArray(result); List<String> jsonValues = new ArrayList<String>(); for (int i = 0; i < jArray.length ...

Tips on transforming truncated surfaces into complete entities

When working in Three.js, I encountered a situation with a 3D object where local clipping planes were used to render only a specific part of the object. However, due to the nature of 3D objects being "hollow" (only rendering the outer surface), when somet ...

Issue with border spacing functionality

I'm having some difficulty with my border spacing in CSS. No matter what size I specify, it doesn't seem to have any effect. I just want to use a border for the top line. Here is my CSS: p { border-spacing: 5000px; text-align: right; ...

angular-recaptcha: Adjusting language based on the website's language update

My website offers three different languages that users can switch between. The language switch functionality is implemented on the client side using JavaScript (AngularJS). I have integrated reCAPTCHA 2 into my website and now I need to update the languag ...

Adding space between elements in Xamarin.Forms ListView

I have a custom Cell type defined in my Xamarin.Forms project: public MyCell() // constructor { var messageLabel = new Label { FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)), FontAttributes ...

Supporting multiple types for matching object structures is a feature in Jest

I'm currently working on a test using jest to verify if an object key is either a string or a number. It seems like a basic task, but surprisingly there isn't much guidance in the documentation. Test Example: test('Checking asset structure ...

Is Express capable of serving static files from a hidden folder with dot file?

I have set up my app to serve a static folder in the following way: app.use('/static', serveStatic(__dirname + '/view/my/static/folder')); Now, I am wondering how to configure the server to serve a hidden folder. For example, if I hav ...

Leverage the power of JSONDecoder to extract embedded JSON data

Is there a way to extract the third-level values from the JSON dataset provided below? { "data": [ { "id": "1669690663119337", "name": "Event1", "attending_count": 17, "cover": { "offset_x": 0, "offset_y": 50, ...

Ways to verify a correct email address using ReactJS

I'm currently working on a project using React.js and Next.js. I'm encountering an issue with handling the Axios response in Next.js as it's displaying "[object Object]" instead of the actual response data. How can I properly handle the resp ...