简体   繁体   中英

How to convert datatable to json object

My datatable is in below format

MCuserid Firsatname address1 address2 city educationinfo institute degree

1760 Rickert vbn addresstwo hyderabad Second College Second Degree

1766 Abhinav jhgjkhk testaddress mtech

1766 Abhinav jhgjkhk testaddress BTech

I need output in following json format in c#

[

{
    "MCUserID" : 1760,
    "FirstName": "Rickert",
    "Address1" : "vbn",
    "Address2" : "address two",
    "city      : "hyderabad"
    "EducationInfo": [
        {
           Institute: "Second College",
           Degree: "Second Degree",
         }
]
},
{    
  "MCUserID"   : 1766,
    "FirstName": "Abhinav",
    "Address1" : "jhgjkhk",
    "Address2" : " test address",
    "city      : ""
    "EducationInfo": [
        {
           Institute: "",
           Degree: "mtech",
         },
         {
           Institute: "",
           Degree: "btech",
         }
        ]

} ]

The problem here is that each row in the DataTable is a simple set of name/value pairs, but you want each person's EducationInfo as another layer in the result JSON. Furthermore you want multiple rows to become a single JSON object if all fields but EducationInfo match.

There isn't going to be a simple "Go()" method that will do this for you out of the box.

I suggest creating Student and EducationInfo classes to hold the information, and aggregate the data yourself into a Student[] array.

Then you simply serialize them using your favorite serializer. As a side effect, this makes debugging so much easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM