C#/PHP read JSON string from PHP into C#

Skythrust

Member
Jul 9, 2019
133
7
Goodmorning people,

I have a web page with some PHP data (JSON) and I would like to read this string in C#.

PHP string; [{"Firstname":"Janet","Middlename":"van","Lastname":"Hope","Key":"12018","Cid":5}]

This string will change when there is a new record for Cid:5 (SELECT TOP 1 * FROM Users WHERE Cid = 5 ORDER BY CreatedOn)

Now I am trying to make a Windows Service which is reading this array, I was thinking to do it like this with a read command

string Firstname = "";
string Middlename = "";
string Lastname = "";
string Key = "";
string Cid = "";


using(WebClient client = new WebClient()) {
string s = client.DownloadString(url);
}

But I have no idea how I can call the right parameters (Firstname,Middlename,Lastname,Key,Cid)

The next step in this call is to insert them in a sqlsrv_connect, but I have no idea how to do that.

Extra Info; I have 2 seperate servers, in a datacenter (1 applicationserver with IIS & SQL with the PHP string, and another one with an other application.) port 1433 (SQL) is closed and cannot be opened for security reason.
There is no LAN connection between those and the future will be is that anyone can install the application (service) to connect application A with application B without portforwarding and just reading the PHP string. Over here they are talking that I need to call it a SOAP intergration.
But I am not familliar with this. So I need to call the PHP string from server A in a service to push it in a insert via a Windows service for server B. I can insert the PHP code but this seems okay I guess.

If there is more information needed let me know.

I would like to use this code in a service, but I am not able to do that
Code:
using (var webClient = new WebClient())
            {
                string json = webClient.DownloadString(new Uri("http://localhost/test.php"));
                var Personal = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Object>>(json);

                foreach (var pv in Personal)
                {
                    string Badge = pv.CredentialNumber;
                    string Firstname = pv.Firstname;
                    string Middlename = pv.Middlename;
                    string Lastname = pv.Lastname;

                    SqlConnection sc = new SqlConnection(GetConnectionStringTemp());
                    {
                        sc.Open();

                        string query = string.Format("INSERT INTO Visitors (Badge,Firstname,Middlename,Lastname) VALUES ('{0}','{1}','{2}','{3}')"

                            , Badge         //0
                            , Firstname      //1
                            , Middlename    //2
                            , Lastname      //3
                            );

                        using (SqlCommand command = new SqlCommand(query, sc))
                        {
                            int countrecords = command.ExecuteNonQuery();
                        }
                        sc.Close();
                    }
                }
            }

when I paste this code in a Winform I am able to recieve the information, and I am able to insert it into a SQLSRV.

I have done some more research and I got this now;



C#:
void JSONtest()

        {

            Uri requestUri = new Uri("http://localhost/test.php");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);

            request.Method = "GET";

            request.BeginGetResponse(new AsyncCallback(ProcessResponse), request);

        }



private void ProcessResponse(IAsyncResult asynchronousResult)

        {

            string ExportFromPHP = string.Empty;

            {

                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult))

                {

                    Stream responseStream = response.GetResponseStream();

                    using (var reader = new StreamReader(responseStream))

                    {

                        ExportFromPHP = reader.ReadToEnd();

                    }

                    responseStream.Close();

                }

                // Do something?

                MessageBox.Show(ExportFromPHP);

            }

        }
 
Last edited:

habtard

New Member
Jan 30, 2020
12
14
Use a JSON nuget package and deserialize it
Code:
using (var webClient = new WebClient())
{
    string json = webClient.DownloadString("whatever"); // will be like: @"{""key1"":""value1"",""key2"":""value2""}";
    var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}

Then access the value by key.
 

Skythrust

Member
Jul 9, 2019
133
7
Use a JSON nuget package and deserialize it
Code:
using (var webClient = new WebClient())
{
    string json = webClient.DownloadString("whatever"); // will be like: @"{""key1"":""value1"",""key2"":""value2""}";
    var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}

Then access the value by key.

Hmm this doesn't work for me.
 

habtard

New Member
Jan 30, 2020
12
14
Change 'whatever' to ' ', if it still doesn't work I'm guessing what you're downloading isn't valid JSON. Can you send the stack trace?
 

Skythrust

Member
Jul 9, 2019
133
7
Change 'whatever' to ' ', if it still doesn't work I'm guessing what you're downloading isn't valid JSON. Can you send the stack trace?

Herewith the code of the php page;

Output PHP: [{"Firstname":"Janet","Middlename":"van","Lastname":"Hope","CredentialNumber":"12018","CustomerId":5}]
Error in C#

Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 2, position 1.
Source=Newtonsoft.Json
StackTrace:
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
at CA4000_EV_Configuration_Tool.Form1.JSONtest() in testl\Form1.cs:line 281
at CA4000_EV_Configuration_Tool.Form1.Form1_Load(Object sender, EventArgs e) in test\Form1.cs:line 480
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Post automatically merged:

Update; just add this code above the void to test;

C#:
        public ObjectTypeList data { get; set; }

        public class ObjectTypeList
        {
            public Dictionary<string, Object> objects { get; set; }
        }

        public class Object
        {
            public string Firstname { get; set; }
            public string Middlename { get; set; }
            public string Lastname { get; set; }
            public string CredentialNumber { get; set; }
            public string CustomerId { get; set; }
        }
 
Last edited:

Skythrust

Member
Jul 9, 2019
133
7
That exception literally tells you what to do.
I see, but I haven't work with JSON before so could you help a little bit in the right direction?
Post automatically merged:

I have figured out that I need to add an object like this;

Where I have add this in the first line { "info": , and } in the last line. I dit check this in a validator and that works. But how can I deploy this in my C# project?
PHP:
{
    "info": [{
        "Firstname": "Jan",
        "Middlename": "de",
        "Lastname": "Hoop",
        "CredentialNumber": "12018",
        "CustomerId": 5
    }]
}
Post automatically merged:

When I start the C# project I get now this message;
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: [. Path 'info', line 2, position 9.'
 
Last edited:

griimnak

You're a slave to the money then you die
Jul 20, 2013
955
794
Your PHP looks really messy, just stick to this template when making your json encode array and try again:
PHP:
<?php
// {"info":{"key1":"val1","key2":"val2","key3":"val3","key4":"val4"}}
$myarray["info"] = array(
  "key1"=>"val1",
  "key2"=>"val2",
  "key3"=>"val3",
  "key4"=>"val4"
);
$myJSON = json_encode($myarray);
echo $myJSON;
?>
Your json object is borked as expressed by the exception you posted, Cannot deserialize the current JSON array (e.g. [1,2,3]) because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
 

Skythrust

Member
Jul 9, 2019
133
7
Your PHP looks really messy, just stick to this template when making your json encode array and try again:
PHP:
<?php
// {"info":{"key1":"val1","key2":"val2","key3":"val3","key4":"val4"}}
$myarray["info"] = array(
  "key1"=>"val1",
  "key2"=>"val2",
  "key3"=>"val3",
  "key4"=>"val4"
);
$myJSON = json_encode($myarray);
echo $myJSON;
?>
Your json object is borked as expressed by the exception you posted, Cannot deserialize the current JSON array (e.g. [1,2,3]) because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Thanks griimnak, but the code is messy because I need to get some data out of SQLSRV :)
Post automatically merged:

Okay Imma bit further.. I can move on now without any errors.

But my messagebox will be empty when I ask a record up..

C#:
        public ObjectTypeList data { get; set; }

        public class ObjectTypeList
        {
            [JsonProperty(PropertyName = "info")]
            public Dictionary<string, Object> info { get; set; }
        }

        public class Object
        {
            [JsonProperty(PropertyName = "Firstname")]
            public string Firstname { get; set; }
            [JsonProperty(PropertyName = "Middlename")]
            public string Middlename { get; set; }
            [JsonProperty(PropertyName = "Lastname")]
            public string Lastname { get; set; }
            [JsonProperty(PropertyName = "Badge")]
            public int CredentialNumber { get; set; }
            [JsonProperty(PropertyName = "CustomerId")]
            public string CustomerId { get; set; }
        }
        
           using (var webClient = new WebClient())
            {
                string json = webClient.DownloadString("http://localhost/intergrator/test.php?uid=U569418&pwd=P497965");
                Object Personal = JsonConvert.DeserializeObject<Object>(json);
                MessageBox.Show("JSON result: " + Personal.Firstname);
            }
Post automatically merged:

Solved.

C#:
public class Object
    {
        public string Firstname { get; set; }
        public string Middlename { get; set; }
        public string Lastname { get; set; }
        public string CredentialNumber { get; set; }
        public string CustomerId { get; set; }
    }

void JSONtest()
    {
        using (var webClient = new WebClient())
            {
                string json = webClient.DownloadString("URL");
                var Personal = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Object>>(json);

                foreach (var pv in Personal)
                {
                    // Do something 
                    // example MessageBox.Show(ev.Firstname);
                }
            }
        }
Post automatically merged:

Your PHP looks really messy, just stick to this template when making your json encode array and try again:
PHP:
<?php
// {"info":{"key1":"val1","key2":"val2","key3":"val3","key4":"val4"}}
$myarray["info"] = array(
  "key1"=>"val1",
  "key2"=>"val2",
  "key3"=>"val3",
  "key4"=>"val4"
);
$myJSON = json_encode($myarray);
echo $myJSON;
?>
Your json object is borked as expressed by the exception you posted, Cannot deserialize the current JSON array (e.g. [1,2,3]) because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

I would like to use this code in a service, but I am not able to do that
Code:
 using (var webClient = new WebClient())
            {
                string json = webClient.DownloadString(new Uri("http://localhost/test.php"));
                var Personal = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Object>>(json);

                foreach (var pv in Personal)
                {
                    string Badge = pv.CredentialNumber;
                    string Firstname = pv.Firstname;
                    string Middlename = pv.Middlename;
                    string Lastname = pv.Lastname;

                    SqlConnection sc = new SqlConnection(GetConnectionStringTemp());
                    {
                        sc.Open();

                        string query = string.Format("INSERT INTO Visitors (Badge,Firstname,Middlename,Lastname) VALUES ('{0}','{1}','{2}','{3}')"

                            , Badge         //0
                            , Firstname      //1
                            , Middlename    //2
                            , Lastname      //3
                            );

                        using (SqlCommand command = new SqlCommand(query, sc))
                        {
                            int countrecords = command.ExecuteNonQuery();
                        }
                        sc.Close();
                    }
                }
            }

when I paste this code in a Winform I am able to recieve the information, and I am able to insert it into a SQLSRV.
 
Last edited:

Users who are viewing this thread

Top