Simon Trewhella
Simon Trewhella

Reputation: 2484

Json.NET and PHP communication

I'm trying to get some communication happening between a C# .NET app and some PHP server side through JSON with Json.NET. I'm POSTing the Json string, but I can't access (or it hasn't sent correctly) the string on the server side. My $_POST variable appears empty, and I don't know what key to use to access the Json string. Can anyone suggest anything?

My C# code:

TestClass ts = new TestClass("Some Data", 3, 4.5);
string json = JsonConvert.SerializeObject(ts);

HttpWebRequest request =
    (HttpWebRequest)WebRequest.Create("http://localhost/testJson.php");
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = json.Length;

StreamWriter sw = new StreamWriter(request.GetRequestStream());
sw.Write(json);   
sw.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string responseJson = sr.ReadToEnd();
sr.Close();

TestClass returnedTS =
    JsonConvert.DeserializeObject<TestClass>(responseJson);

My PHP Code:

<?php
    require("TestClass.php");
    $json = json_decode($_POST);
    $ts = new TestClass();
    $ts->someString = $json['someString'];
    $ts->someDouble = $json['someDouble'];
    $ts->someInt = $json['someInt'];
    $return_json = json_encode($ts);
    echo $return_json;
?>

My output:

<b>Warning</b>:  json_decode() expects parameter 1 to be string, array given in
<b>C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\testJson.p
hp</b> on line <b>4</b><br />
{"someString":null,"someInt":null,"someDouble":null}

Upvotes: 1

Views: 3967

Answers (1)

user1626993
user1626993

Reputation:

You have to use application/json instead of application/x-www-form-urlencoded.

Maybe that helps!

Upvotes: 3

Related Questions