Understanding how to break down intricate JSON strings into classes using either VB or C# programming languages

I have a JSON string that needs to be parsed and eventually stored in database tables. My plan is to parse it into VB .NET classes (objects) and then store the data in the tables. I have Newtown imported into my .NET environment, but I'm not very familiar with it in order to effectively break down the JSON into objects.

{
    "phenotype_results": [
        {
            "gName": "CYP2",
            "gtype": "*11",
            "otype": "normal",
            "adjustedPhe": "poor",
            "note": "string"
        },
        {
            "gName": "CYP2",
            "gtype": "*113",
            "otype": "normal",
            "adjustedPhe": "poor",
            "note": "string"
        },
        {
            "gName": "CYP2",
            "gtype": "**1",
            "otype": "normal",
            "adjustedPhe": "poor",
            "note": "string"
        },
        
    ],
    "medics": [
        {
            "mName": "flax",
            "Adj": [
                {
                    "eName": "CYP",
                    "eType": null,
                    "substrate": true
                },
                {
                    "eName": "CYP3",
                    "eType": null,
                    "substrate": true
                },
                {
                    "eName": "CYP4",
                    "eType": null,
                    "substrate": true
                },
            ],
            "associations": [
                "CYP20"
            ],
            "recommendation": "No action required.",
            "strength": "",
            "source": "DPWG",
            "source_url": "https://www.pha.xom",
            "pathway_url": "https://www.xxx.yyy"
        },
        {
            "newName": "carba",
            "geneAdjustments": [
                {
                    "geneName": "CYP2B6",
                    "adjType": "Inducer",
                    "substrate": false
                },
                {
                    "geneName": "CYP3A5",
                    "adjType": "Inducer",
                    "substrate": true
                },
                {
                    "eName": "CYP4",
                    "eType": null,
                    "substrate": true
                }                
            ],
            "assoc": [
                "HLA-A",
                "HLA-B"
            ],
            "rec": "If cccc do yyy.",
            "strength": "STRONG",
            "source": "CPIC",
            "source_url": "https://www.p",
            "pathway_url": "https://www"
        }
    ],
    "recommendations": [
        {
            "associ": [
                "HLA1"
            ],
            "recommendation": "Use per stand.",
            "strength": "STRONG",
            "medName": "vir",
            "source": "CPIC",
            "actionable": false,
            "medType": "Anti-Infective"
         
        },
         {
            "associ": [
                "HLA1"
            ],
            "recommendation": "Use per stand.",
            "strength": "STRONG",
            "medName": "vir",
            "source": "CPIC",
            "actionable": false,
            "medType": "Anti-Infective"
         
        }
        
    ]
}

Please review the above JSON file and let me know if you have any questions.

Thank you!

Answer №1

To start, it's important to outline your objects. If you haven't already established the necessary classes, I recommend using a helpful tool like this one. Sometimes taking shortcuts is just efficient.

https://json2csharp.com/

Once you've mapped out your object structure, Entity Framework can assist in storing them in your database. Personally, I struggle with this aspect so I usually seek assistance from others who excel in that area.

Answer №2

To extract the desired data, create a Json object using the code snippet provided below:

Feel free to utilize any tools you prefer for this task.

 Try
         'your json
         Dim jsonString = System.IO.File.ReadAllText("D:\Json.txt")
         Dim dto As TestDTO

         dto = JsonConvert.DeserializeObject(Of TestDTO)(jsonString)

        'Deserialize DataSet
        'Dim dto As DataSet
        'dto = JsonConvert.DeserializeObject(Of DataSet)(jsonString)

         Dim phenotypeList As List(Of phenotype_resultsDTO) = dto.phenotype_results

         For i = 0 To phenotypeList.Count - 1

            Debug.WriteLine(phenotypeList(i).gName)
            Debug.WriteLine(phenotypeList(i).gtype)

         Next
      Catch ex As Exception
         MsgBox(ex.ToString)
      End Try

'JSON Sample

Public Class TestDTO

   Public Property phenotype_results As IList(Of phenotype_resultsDTO)
   Public Property medics As IList(Of medicslDTO)

End Class

Public Class phenotype_resultsDTO

   Public Property gName As String
   Public Property gtype As String

End Class

Public Class medicslDTO

   Public Property mName As String
   Public Property Adj As IList(Of AdjDTO)

End Class

Public Class AdjDTO

   Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click


      Try

         'your json
         '    Dim jsonString = System.IO.File.ReadAllText("D:\Json.txt")

         Dim jsonString As String = " {'actions' : { 'VRA-B*58:00': [ 'allopu' ], 'VKO1': [ 'film1' ], 'CYP2': [ 'song2' ], 'HLA-3': [ 'dance3', 'dance4' ], 'ETC': [ 'tac' ] }} "


         Dim myDeserializedClass As Roo = JsonConvert.DeserializeObject(Of Roo)(jsonString)


         Dim action As Actions = myDeserializedClass.actions


         For Each item As String In action.VRAB5800
            Console.WriteLine(item)
         Next

         For Each item As String In action.VKO1
            Console.WriteLine(item)
         Next

         For Each item As String In action.CYP2
            Console.WriteLine(item)
         Next

         For Each item As String In action.HLA3
            Console.WriteLine(item)
         Next

         For Each item As String In action.ETC
            Console.WriteLine(item)
         Next

      Catch ex As Exception
         MsgBox(ex.ToString)
      End Try


   End Sub


End Class


Public Class Actions
   <JsonProperty("VRA-B*58:00")>
   Public Property VRAB5800 As List(Of String)
   Public Property VKO1 As List(Of String)
   Public Property CYP2 As List(Of String)
   <JsonProperty("HLA-3")>
   Public Property HLA3 As List(Of String)
   Public Property ETC As List(Of String)
End Class

Public Class Roo
   Public Property actions As Actions

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

Solving issues with event handling through addEventListener within a functional component in React

I am working on a React component that includes an input field and I want to implement a character autocompletion feature. The idea is that when a user types " or ', the same character should be automatically added again, with the cursor placed i ...

When package.json is imported, files are not compressed

Currently, I am working on developing a cli package and when it comes to displaying the version, I am utilizing the version imported from package.json. Upon running tsc, the structure of the dist folder appears as follows: /dist --/package.json --/README. ...

Issue encountered while attempting to pass a function within the data in React

I've encountered an issue while trying to pass a function called sectionOne and then calling it from another component. The error message I received is quite confusing. Error: Warning: Functions are not valid as a React child. This may happen if you r ...

An issue related to AngularJS and the injection of ui-bootstrap components has been encountered

I'm encountering an issue with injection errors in my code, and unfortunately, the debugger in Firefox isn't providing much help. Here are snippets of the code: This is the Controller file causing the error: App.controller('ModalInstanceCt ...

Interactive window allowing the user to closely examine code

Hey guys, I need your help with something Is there a way (PHP / jQuery) that allows me to zoom in on my code? Similar to how lightbox works for images. I specifically want to zoom in on dynamic code while using Yii's CListView. I'm thinking of ...

The JavaScript function exclusively reveals the final element, which is Three.js

I'm currently working on a fence generator function using Three.js, but for some reason, my function is only returning the last fence created. It's really puzzling to me... function createFence(nb){ var i; var position = -5; var loadingMan ...

Having problems getting my fixed header to work on my datatable. What could be the

Struggling to make my data table Thead sticky? I attempted using position: fixed;, top: 0; with CSS but it only worked in Firefox, not Chrome, Edge, or Opera. Here is an excerpt of my Ajax code: "stateSave": false, "orderCellsTop&quo ...

The issue of mapping C# optional parameters with JSON data in an Ajax request, specifically when they have the same name but different types

Having trouble with the json data Parameters of an ajax request not matching properly for an optional parameter of a c# method $.ajax({ url: '/CusotmerManagement/Cusotmer/GetCusotmerByDisplayId/', ...

``Unresolved issue: Sending emails using Sendgrid and Firebase not working in production through Netlify

For a simple contact form, I am utilizing Nuxt, Sendgrid, and Firebase. Netlify is being used for hosting the project. The contact form works perfectly fine locally and sends emails without any issues. However, once I push the project to Netlify, the email ...

The action of POSTing to the api/signup endpoint is

Currently delving into the MEAN stack, I have successfully created a signup api. However, when testing it using POSTMAN, I encountered an unexpected error stating that it cannot POST to api/signup. Here is a snapshot of the error: Error Screenshot This ...

Interested in exporting a Log-based Metric in JSON Style

I manage multiple GCP projects that are all centrally monitored by a main project. I need to implement a Log-based metric in each of these individual projects. The structure of the metric is consistent across all projects, except for the project name bei ...

"Receiving an 'undefined index' error when attempting to post in Ajax with

Need help with sending data from client to server using AJAX in PHP. I am facing an issue when trying the following code: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascrip ...

Transmit information to the controller using jQuery in a C# MVC environment

Here is my jQuery script code snippet. The script works perfectly and stores the data array/object in a variable called dataBLL. var dataBLL = []; $('#mytable tr').each(function (i) { dataBLL.push({ id: $(this).find('td:eq(0)').text( ...

Is it advisable to initiate an AJAX call and allow the browser to cancel the request if needed?

When an AJAX request is made, it typically appears in the network tab in Chrome. However, if a client-based redirect occurs at the same time, the AJAX request may be cancelled. But does this mean that the request still reaches the server and executes as ...

Angular failing to update $scope variable within controller

I need to implement a directive that allows file uploading directly to the browser angular.module('angularPrototypeApp') .directive('upload', ['$parse', function ($parse) { return { restrict: 'A', scope: fal ...

The function designed to create in-line TailwindCSS classNames may work inconsistently in React and NextJS environments

Currently, I am utilizing TailwindCSS to style a web application. One frustrating aspect is that when attempting to add before: and after: pseudo-elements, it must be done individually. For instance, take the navigation drop-down button styling: <span ...

What is the optimal placement for promises in Angular: Factory or Controller?

In my application, I have a basic factory to manage API calls. Currently, the structure looks like this: .factory('apiFactory', function($http){ var url = 'http://192.168.22.8:8001/api/v1/'; return { getReports: function() { ...

Using jQuery's .load() method is like including a file in a

Currently, Im working on revamping a company website that comes equipped with its very own CMS. Unfortunately, we are restricted from accessing the server configuration and FTP, which means I am limited to running only client-side files like HTML/CSS/J ...

Utilizing Directives for DOM Manipulation in AngularJS

At this moment, I have a functional Angular app that is working properly. However, I am currently performing DOM manipulation within my controller instead of utilizing directives as recommended. My concern is, how can I correctly implement this functionali ...

Merge a pair of values into an object using a JOLT conversion

I am new to using Jolt and I have a source format that was generated from some software but it lacks good structure. I want to transform it so that each piece of text ("First text" and "Second text") is associated with a link ("First text -> Link of fir ...