web request json response parse to dataset in vb.net

196 Views Asked by At

I am using web request to call api in web service wwith vb.net, I was trying to parse json response to dataset and i did the parsing part. In the json response have many records and it only parse the first record, how do i parse more record?

json Response:

"List": [
        {
            "ID": "1",
            "Name": "Karen",
            "PhoneNo": "0010000114248"
        },
        {
            "ID": "2",
            "Name": "Krystal",
            "PhoneNo": "0010000114250"
        }
    ]

Code:

Dim apiUrl = ConfigurationManager.AppSettings("Url")
            Dim request As WebRequest = WebRequest.Create(apiUrl)
            Dim body = "{""PageIndex"": ""1"", ""PageSize"": ""10000""}"
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(body)
            request.Method = "POST"
            request.ContentType = "application/json"
            request.ContentLength = byteArray.Length
            Dim dataStream As Stream = request.GetRequestStream()
            dataStream.Write(byteArray, 0, byteArray.Length)
            dataStream.Close()
            Dim sr As StreamReader = New StreamReader(request.GetResponse().GetResponseStream)
            Dim rte As String = sr.ReadToEnd()
            Dim jsonObject As JObject = JObject.Parse(rte)
            Dim id = If(jsonObject.SelectToken("List")(0)("ID") Is Nothing, "", jsonObject.SelectToken("List")(0)("ID").ToString)
            Dim name = If(jsonObject.SelectToken("List")(0)("Name") Is Nothing, "", jsonObject.SelectToken("List")(0)("Name").ToString)
            Dim phoneNo = If(jsonObject.SelectToken("List")(0)("PhoneNo") Is Nothing, "", jsonObject.SelectToken("List")(0)("PhoneNo").ToString)
            Dim dt As DataTable = New DataTable("Result")
            dt.Columns.Add("id")
            dt.Columns.Add("name")
            dt.Columns.Add("phoneNo")
            
            dt.Rows.Add(id, name, phoneNo)
            Dim ds As DataSet = New DataSet("Result")
            ds.Tables.Add(dt)
            Return ds.GetXml()

It only get the first record, if i have more than 10000 records and how do i parse more records into dataset?

1

There are 1 best solutions below

2
Serge On

you need just one line of code

Dim ds As DataSet = JsonConvert.DeserializeObject(Of DataSet)(rte)

// if you need a ds name
ds.DataSetName = "Result"