Reputation: 621
I'm actually trying to parse a JSON request response from my PHP web service into a c# object.
I've found some code sample using json.net and then I made this code from my Wine class :
public Wine(string json)
{
JObject jObject = JObject.Parse(json);
BottleName = (string)jObject["name"];
Category = (string)jObject["category"];
Prize50 = Double.Parse((string)jObject["prize_50"]);
Prize75 = Double.Parse((string)jObject["prize_75"]);
Prize150 = Double.Parse((string)jObject["prize_150"]);
Prize300 = Double.Parse((string)jObject["prize_300"]);
}
It's work perfectly if a have only 1 response like
"{\"id\":\"2\",\"name\":\"Pinot noir\",\"loc_wine\":\"",\"category\":\"Red\",\"prize_50\":\"12.800000\",\"prize_75\":\"16.500000\",\"prize_150\":\"0.000000\",\"prize_300\":\"0.000000\"} "
But I hav trouble when I have another Json string in my json response and I wish know how can I deal with it?
And I have sometimes null fields, how can I ignore them?
Thank you for helping ! :-)
P.S. If needed, this is how I send my datas from my PHP file :
$req = "SELECT *
FROM t_wine
WHERE name= \"Pinot noir\""; // for test purpose
$res = mysqli_query($connection, $req);
while($data= mysqli_fetch_assoc($res)) {
extract ($data);
echo json_encode($data);
}
Upvotes: 0
Views: 287
Reputation: 4296
Ok, if you are trying to handle getting multiple instances of Wine
, and you want to ignore null values in json.net, you can do this:
var settings = new JsonSerializerSettings{ NullValueHandling = NullValueHandling.Ignore };
}
JsonConvert.DeserializeObject<IEnumerable<Wine>>(response.ToString(), settings);
Upvotes: 0
Reputation: 13483
If there is more than one row returned from the mysqli_fetch
statement, then echoing the json response for each row without putting the response in an array will give you bad JSON. You're response basically would look like this:
{..some data...}{...some data...}
So let's take advantage of the array structure of JSON. Change your PHP code to output like an array
$res = mysqli_query($connection, $req);
echo "[";
while($data= mysqli_fetch_assoc($res)) {
extract ($data);
echo json_encode($data);
echo ",";
}
echo "]";
That will give you something like this:
[{...some data...},{...some data...},]
Keep in mind, this is rough. You'll need to trim that last comma before the end bracket. But that's a valid JSON array.
You'll also need to modify your C# to process the jObject as an array of objects instead of one object.
Upvotes: 2