Helladen Helladen - 1 year ago 75
C# Question

Response JSON Request

I am trying to use JSON .NET with a WebRequest, to retrieve JSON using "GET". Essentially, I am stuck on the parsing part and grabbing the item to test. The WebResponse, how would I go about retrieving the JSON file using the webResponse? The API.php is a way for me to connect to a website database to login. If the login is successful, it returns a JSON object.

string sAddress = "http://hitsparkinteractive.com/api.php";

// Get the hash
string addrParams = "action=authenticate";
addrParams += "&username=" + user;
addrParams += "&password=" + pwd;

WebRequest webRequest = WebRequest.Create(sAddress + "?" + addrParams);
webRequest.Timeout = 3000;
WebResponse webResponse = webRequest.GetResponse();

JObject retJSON;
retJSON = JObject.Parse(webResponse.ToString());

This is working code from Visual Basic 6, that uses WinHTTPRequest.

Private Function AuthenticateUser(ByVal index As Long, ByVal Username As String, ByVal Password As String) As Long
Dim HTTP As WinHttpRequest, sAddress As String, addrParams As String
Dim JSONParser As Object, retJSON As String, ErrorCode As String, ErrorMsg As String

On Error Resume Next

sAddress = "http://hitsparkinteractive.com/api.php"

addrParams = "action=authenticate"
addrParams = addrParams & "&username=" & Username
addrParams = addrParams & "&password=" & Password

Set HTTP = New WinHttpRequest
HTTP.Open "GET", sAddress & "?" & addrParams, False
HTTP.SetTimeouts 250, 250, 250, 3000

retJSON = HTTP.ResponseText
Set HTTP = Nothing

' Parse your JSON here.
Set JSONParser = JSON.parse(retJSON) ' What is returned is Scripting.Dictionary object
If Not JSONParser Is Nothing Then
If JSONParser.Exists("error") Then ' keys are case sensitive I believe
' We errored out
ErrorCode = JSONParser.Item("error")

Select Case ErrorCode
Case "3"
AuthenticateUser = 1

Case Else
AuthenticateUser = 2
End Select

ErrorMsg = JSONParser.Item("message")
Call AlertMsg(index, ErrorMsg)
Exit Function
ElseIf JSONParser.Exists("hash") Then ' we got our hash, sucessfully authenticated
TempPlayer(index).Hash = JSONParser.Item("hash")
AuthenticateUser = 0
Exit Function
End If
AuthenticateUser = 3
Call AlertMsg(index, "Request timed out, please try again.")
Exit Function
End If
End Function

Answer Source

JSON is actually a string, representing serialized objects.

ToString returns a string representation of an object -- probably something like System.Web.HttpResponse.

What you need is the text of the response, and that you can get via the GetResponseStream.