-
Jul 18th, 2020, 06:02 AM
#1
Thread Starter
Hyperactive Member
Get and read JSON data
hi
i am using asp.net 2010
i have a url from where i would be getting the json data
i tried a lot of options but all are using
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
but the prob. is
when i am using
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
it says : jobject is ambiguous in the namespace newtonsoft.json.linq
same for jtoken and JProperty
it seems Newtonsoft.Json does not support vs 2010
following is the error when i try to upgrade the newtonsoft in package manager
Install-Package : The 'Newtonsoft.Json 12.0.1' package requires NuGet client version '2.12' or above, but the current NuGet version is '2.8.60318.667'.
At line:1 char:2
+ Install-Package Newtonsoft.Json -Version 12.0.1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: ( [Install-Package], NuGetVersionNotSatisfiedException
+ FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
below is the data that i would be getting
Code:
Failed result:
{"failed":0}
Success result :
{
"information": {
"1": {
"ICMR_no": "22",
"name": "abc",
"contact_number": "12345",
"gender": "Female",
"address": "thane1",
"age": "2",
"health_center": "Health Post - 2",
"prabhag_name": "Prabhag - 2",
"camp": "Camp 1",
"covid_detect_date": "2020-07-16",
"patient_status": "positive",
"record_date": "2020-07-18 16:44:15"
}
}
}
it could be failed or information
and in information it could me "n" no of records.
very much confused. pls. guide.
below is the code i have tried
Code:
Dim json As String = "http://domainname.in/Clientapi/format_d_details"
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "failed"
ShowMessageNew("No Records Found", "No Data")
Case "information"
For Each msg As JObject In item.Values
Dim drNewRow As DataRow = dTable.NewRow
drNewRow.Item("ICMR_no") = msg("ICMR_no")
drNewRow.Item("name") = msg("name")
drNewRow.Item("contact_number") = msg("contact_number")
drNewRow.Item("gender") = msg("gender")
drNewRow.Item("address") = msg("address")
drNewRow.Item("age") = msg("age")
drNewRow.Item("health_center") = msg("health_center")
drNewRow.Item("prabhag_name") = msg("prabhag_name")
drNewRow.Item("camp") = msg("camp")
drNewRow.Item("covid_detect_date") = msg("covid_detect_date")
drNewRow.Item("status") = msg("status")
drNewRow.Item("record_date") = msg("record_date")
drNewRow.Item("GatheredOn") = Format(Today.Date, "dd-MMM-yyyy")
dTable.Rows.Add(drNewRow)
'Dim first_name As String = msg("first_name")
'Dim last_name As String = msg("last_name")
Next
End Select
Next
dgCases.DataSource = dTable
dgCases.DataBind()
Session.Add("PositiveCases", dTable)
dgCases.DataSource = dTable
dgCases.Visible = True
dgCases.DataBind()
pls. guide. its a bit urgent have spent a lot of time searching
i am open to even creating a desktop app or web app whatever i am guided to.
thanks a lot
The only time you run out of chances is when you stop taking them.
The mind is like a parachute.
It doesn’t work unless it’s open.
-
Jul 18th, 2020, 06:13 AM
#2
Re: Get and read JSON data
If you are going to use Newtonsoft.Json it might be a lot easier to create classes for the data structures you are reading from Json and let the tool handle parsing the actual json data - https://www.newtonsoft.com/json/help...lizeObject.htm gives a basic example but the principle is the same for more complex data structures.
https://jsonutils.com/ is a pretty decent tool for converting json into an appropriate VB class as well.
e.g. the json you posted above results in
Code:
Public Class 1
Public Property ICMR_no As String
Public Property name As String
Public Property contact_number As String
Public Property gender As String
Public Property address As String
Public Property age As String
Public Property health_center As String
Public Property prabhag_name As String
Public Property camp As String
Public Property covid_detect_date As String
Public Property patient_status As String
Public Property record_date As String
End Class
Public Class Information
Public Property 1 As 1
End Class
Public Class Example
Public Property information As Information
End Class
So although you might need to sort the first class' name out it has more or less done the hard work for you.
-
Jul 18th, 2020, 06:50 AM
#3
Thread Starter
Hyperactive Member
Re: Get and read JSON data
Originally Posted by PlausiblyDamp
If you are going to use Newtonsoft.Json it might be a lot easier to create classes for the data structures you are reading from Json and let the tool handle parsing the actual json data - https://www.newtonsoft.com/json/help...lizeObject.htm gives a basic example but the principle is the same for more complex data structures.
https://jsonutils.com/ is a pretty decent tool for converting json into an appropriate VB class as well.
e.g. the json you posted above results in
Code:
Public Class 1
Public Property ICMR_no As String
Public Property name As String
Public Property contact_number As String
Public Property gender As String
Public Property address As String
Public Property age As String
Public Property health_center As String
Public Property prabhag_name As String
Public Property camp As String
Public Property covid_detect_date As String
Public Property patient_status As String
Public Property record_date As String
End Class
Public Class Information
Public Property 1 As 1
End Class
Public Class Example
Public Property information As Information
End Class
So although you might need to sort the first class' name out it has more or less done the hard work for you.
Thanks for ur quick response.
but the prob. is as i said i am not able to use newtonsoft.json
following is the msg. i am getting
jobject is ambiguous in the namespace newtonsoft.json.linq
same for jtoken and JProperty
so unless i do the below :
Code:
Dim json As String = "http://umccovid.in/Clientapi/format_d_details"
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
For Each item As JProperty In data
i am will not be able to get the data due to " object is ambiguous in the namespace newtonsoft.json.linq "
hence i am very much stuck
thanks
The only time you run out of chances is when you stop taking them.
The mind is like a parachute.
It doesn’t work unless it’s open.
-
Jul 18th, 2020, 09:42 AM
#4
Thread Starter
Hyperactive Member
Re: Get and read JSON data
got it working to some extend. changed from vs2010 to vs2017
below is the code i have done:
Code:
Dim json As String = "http://domainname/Clientapi/format_d_details"
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("http://domainname/Clientapi/format_d_details"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As Object = JObject.Parse(rawresp)
Dim mFailed As String = If(jResults("failed") Is Nothing, "Record Found", jResults("failed").ToString)
If mFailed <> "0" Then
Dim ser As JObject = JObject.Parse(rawresp)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "failed"
Dim mMsg As String = "Failed"
Case "information"
For Each msg As JObject In item.Value
Dim drNewRow As DataRow = dTable.NewRow
drNewRow.Item("ICMR_no") = msg("ICMR_no")
drNewRow.Item("name") = msg("name")
drNewRow.Item("contact_number") = msg("contact_number")
drNewRow.Item("gender") = msg("gender")
drNewRow.Item("address") = msg("address")
drNewRow.Item("age") = msg("age")
drNewRow.Item("health_center") = msg("health_center")
drNewRow.Item("prabhag_name") = msg("prabhag_name")
drNewRow.Item("camp") = msg("camp")
drNewRow.Item("covid_detect_date") = msg("covid_detect_date")
drNewRow.Item("status") = msg("status")
drNewRow.Item("record_date") = msg("record_date")
drNewRow.Item("GatheredOn") = Format(Today.Date, "dd-MMM-yyyy")
dTable.Rows.Add(drNewRow)
'Dim first_name As String = msg("first_name")
'Dim last_name As String = msg("last_name")
Next
End Select
Next
End If
my prob now is i can read the data if it contains {"failed":0}
but the prob. is that the person sending me the data is putting the record no. too in the data. the data that is coming is as below:
{"information": {"1":{"ICMR_no":"22","name":"abc","contact_number":"12345","gender":"Female","address":"thane1","age":"2" ,"health_center":"Health Post - 2","prabhag_name":"Prabhag - 2","camp":"Camp 1","covid_detect_date":"2020-07-16","patient_status":"","record_date":"2020-07-18 12:17:13"}, "2":{"ICMR_no":"1001","name":"testing info","contact_number":"8959596595","gender":"Male","address":"ulhasnagar","age":"28","health_center ":"Health Post - 3","prabhag_name":"Prabhag - 3","camp":"Camp 2","covid_detect_date":"2020-07-01","patient_status":"Positive","record_date":"2020-07-18 18:10:42"}}}
the record no. is giving me prob.
Code:
For Each msg As JObject In item.Value
is showing me error
error is :
System.InvalidCastException: 'Unable to cast object of type 'Newtonsoft.Json.Linq.JProperty' to type 'Newtonsoft.Json.Linq.JObject'.'
confused a lot
pls. guide.
thanks
The only time you run out of chances is when you stop taking them.
The mind is like a parachute.
It doesn’t work unless it’s open.
-
Jul 27th, 2020, 12:59 AM
#5
Re: Get and read JSON data
The error means that you are casting the each row to
Code:
For Each msg As JObject In item.Value
And then assignning to
Code:
drNewRow.Item("address") = msg("address")
drNewRow.Item("age") = msg("age")
drNewRow.Item("health_center") = msg("health_center")
drNewRow.Item("prabhag_name") = msg("prabhag_name")
This appears to be some of the value of drNewRow is of 'Newtonsoft.Json.Linq.JProperty' and hence it is not working
Please mark you thread resolved using the Thread Tools as shown
-
Jul 27th, 2020, 09:23 AM
#6
Thread Starter
Hyperactive Member
Re: Get and read JSON data
thanks for ur guidance i got it working i asked the provider of the json data to remove the record count and that did the job. now with the same code above i am able to gather the data.
but facing a new prob. now. first what i did was created a web app.
now my requirement is actually i need to gather the data into a web service.
what i did was create a web service to try out a smaller part of the app.
here is what i have did :
Code:
<WebMethod>
Public Function SubGetVisitorsListNew(ByVal jsonResult As JObject) As String
Dim mMsg As String = "Done"
MyConConnection.Open()
Try
Dim details = JObject.Parse(jsonResult)
Dim ser As JObject = JObject.Parse(jsonResult)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "visitors"
For Each msg As JObject In item.Values
mCmd = "INSERT INTO SurveyVisitorsData "
mCmd = mCmd & " (FamilyHeadSerialNo, Name,Age, AgeDetails, Sex, IfUNRResident) "
mCmd = mCmd & " VALUES "
mCmd = mCmd & " (@mFamilyHeadSerialNo, @mName,@mAge, @mAgeDetails, @mSex, @mIfUNRResident) "
cmd = New SqlCommand(mCmd, MyConConnection)
cmd.Parameters.AddWithValue("@mFamilyHeadSerialNo", msg("FamilyHeadSerialNo"))
cmd.Parameters.AddWithValue("Name", msg("Name"))
cmd.Parameters.AddWithValue("contact_number", msg("contact_number"))
cmd.Parameters.AddWithValue("Age", msg("Age"))
cmd.Parameters.AddWithValue("AgeDetails", msg("AgeDetails"))
cmd.Parameters.AddWithValue("Sex", msg("Sex"))
cmd.Parameters.AddWithValue("IfUNRResident", msg("IfUNRResident"))
cmd.ExecuteNonQuery()
Next
End Select
Next
Catch ex As Exception
mMsg = ex.Message.ToString
End Try
MyConConnection.Close()
Return mMsg
End Function
when i am running the app. i am getting the following error :
You must implement a default accessor on Newtonsoft.Json.Linq.JObject because it inherits from ICollection.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: You must implement a default accessor on Newtonsoft.Json.Linq.JObject because it inherits from ICollection.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: You must implement a default accessor on Newtonsoft.Json.Linq.JObject because it inherits from ICollection.]
System.Xml.Serialization.TypeScope.GetDefaultIndexer(Type type, String memberInfo) +5361982
System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference) +1475
System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError) +157
System.Xml.Serialization.XmlReflectionImporter.ImportMemberMapping(XmlReflectionMember xmlReflectionMember, String ns, XmlReflectionMember[] xmlReflectionMembers, Boolean rpc, Boolean openModel, RecursionLimiter limiter) +71
System.Xml.Serialization.XmlReflectionImporter.ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, String ns, Boolean hasWrapperElement, Boolean rpc, Boolean openModel, RecursionLimiter limiter) +300
pls. guide.
thanks
The only time you run out of chances is when you stop taking them.
The mind is like a parachute.
It doesn’t work unless it’s open.
-
Jul 27th, 2020, 11:18 PM
#7
Re: Get and read JSON data
Looks like you are getting exception in this part of code.
Code:
Dim details = JObject.Parse(jsonResult)
You are trying to parse jsonResult to JObject , and this appears to be not supported.
Try to convert the jsoresult to xml and parse the nodes
Example
Please mark you thread resolved using the Thread Tools as shown
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|