Convert json to datatable vb

后端 未结 2 1358
梦毁少年i
梦毁少年i 2021-01-19 14:28

Good morning, today i was trying to convert my json to datatable.

This is what i\'m trying to do

    Dim webclient_server7 As New System.Net.WebClien         


        
2条回答
  •  一生所求
    2021-01-19 15:07

    After almost a year of practice with json i decided to answer my question. If you're actually trying to deserialize a json into a datatable we can assume you're using vb.net or c# (in other words visual studio).

    To achive this task follow my list:

    0) Download and install Newtonsoft.json from Nuget
    1) Copy your raw json
    2) create a new class in your solution and name it as you want. (example: MyDatatable.vb)
    3) In the Mydatatable.vb page : Modify -> Paste Special -> Paste JSON as class (this is the key)

    At this point visual studio will start creating a bunch of classes that will help newtonsoft to deserialize your json into the main object. In my case the main object was a class named Table like you can see below :

    "{\r\n \"Table\": [\r\n {\r\n \"IdOwner\": \"Davide\",\r\n \"tag_id\": 1,\r\n \"tag_type\": \"3\",\r\n \"tag_group\": \"Group_2\",\r\n \"tag_name\": \"Alfa\",\r\n \"tag_sequence\": 123458,\r\n \"tag_description\": \"Description_2\",\r\n \"tag_short_descritpion\": \"Desc_2\",\r\n \"tag_um\": \"kg\",\r\n \"tag_active\": true,\r\n \"tag_colle

    4) At this point you will have

    • A class file named MyDatatable.vb containing many other classes like (*Table)
    • Newtonsoft reference installed on your project

    this will allow you to deserialize your json with 2 instructions which are:

    Dim strMyJson as string = [your raw json here]
    Dim tbFinalObject as Table = Newtonsoft.json.jsonconver.deserializeObject(of Table)(strMyJson)
    

    So in your tbFinalObject Object you'll have your json deserialized. Note: if the second instruction gives you an error like 'expected some char at line x' this may be because your json needs to be deserialized into a string before to be deserialized into another object so you should have a set of instructions like below:

     Dim strMyJson as string = [your raw json here]
     Dim strMyJson as string = Newtonsoft.json.jsonconvert.deserializeObject(of string)([your raw json here])
     Dim tbFinalObject as Table = Newtonsoft.json.jsonconvert.deserializeObject(of Table)(strMyJson)
    

    That's how i solve most of my issues with json and vb.net deserializations.

    Further Notes: When you paste a json as class visual studio will automatically create object and create some property as arrays. I use to replace arrays with lists because i found that some old versions of newtonsoft have some problems deserializing json into arrays.

提交回复
热议问题