简体   繁体   中英

Error reading Json from PHP into C#

I'm receiving this error when trying to read a JObject in C# from PHP , it is the result of a basic query "SELECT * FROM items"...

Unexpected character encountered while parsing value: S. Path '', line 0, position 0.

PHP

$query = ($_POST["test"]);

if ($result = $mysqli->query($query)
{
    $jsonResult = json_encode($result);
}   

echo $jsonResult;

C#

public JObject GetThat()
{
    HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

    Stream Answer = WebResp.GetResponseStream();

    string phpResponse = Answer.ToString();
    JObject myResult = JObject.Parse(phpResponse);

    return myResult;
}

What am I doing wrong? Thanks.

The problem is that Answer.ToString() won't return the stream contents as a string. Try something like this.

public JObject GetThat()
{
    HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

    string phpResponse = string.Empty;
    using(StreamReader rdr = new StreamReader(WebResp.GetResponseStream()))
        phpResponse = rdr.ReadToEnd();
    }

    JObject myResult = JObject.Parse(phpResponse);

    return myResult;
}

It turns out the problem was the array type.

$row = $result->fetch_array(MYSQLI_NUM);

does not work, but

$row = $result->fetch_array(MYSQLI_BOTH);

and

$row = $result->fetch_array(MYSQLI_ASSOC);

do. Does anyone have any idea why? Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM