0

I'm doing an server-side validation for iOS receipt.

I want to send back 2 things to the client:

-the response code from Apple (an int)
-all the product identifiers (possibly an array or object)

My C# receiver class needs one int (the response code) and all the product identifiers, possibly as an array or object.

The problem in an array is that I would have to define the number of elements beforehand, which i can't guess.

For now I have this:

$obj = (object) [
    'status' => $status,
    'productIds' => ???????];

echo json_encode($obj);

How should I go about this?

Josiah
  • 207
  • 3
  • 13
alexx0186
  • 1,557
  • 5
  • 20
  • 32
  • *"The problem in an array is that I would have to define the number of elements beforehand"* - Why? – GolezTrol Jun 08 '18 at 21:03
  • make it a list, not an array, then you don't have to specify the maximum amount of elements. – Jeff Jun 08 '18 at 21:08
  • Thanks for your responses. In C# I get "Array creation must have array size or array initializer" – alexx0186 Jun 08 '18 at 21:26
  • Do I build an array in PHP or an object? – alexx0186 Jun 08 '18 at 21:27
  • _Side note:_ Casting the array as an object before json_encode is totally redundant. – M. Eriksson Jun 08 '18 at 21:34
  • If you do as @Jeff suggests and define a List instead of an Array in C#, you won't need to define a length. https://stackoverflow.com/questions/599369/array-of-an-unknown-length-in-c-sharp – M. Eriksson Jun 08 '18 at 21:36
  • How do your PHP code and the C# code communicate? If you want to use a JSON encoded result, is there anything not working with the given code? Why do you need to cast the array to an object first before encoding it? – Nico Haase Aug 10 '21 at 09:40

1 Answers1

0

Helloooo!

I am by all meanings no php expert so please forgive me if the code looks not that good.

PHP Part:

<?php

$status = 0;
$productIDs = array();

//i dont know how you get the data.. so, loopy loop
for ($x = 1; $x <= 20; $x++)
{
    $productIDs[] = $x;
}

//genereate object and fill 
$obj = new stdClass;
$obj->status = $status;
$obj->productIDs = $productIDs;

//encode object to json and show it
echo json_encode($obj);

?>

C# Part

Creating a class to create object from JSON

public class myClass
{
     public string status { get; set; }
     public int[] productIDs { get; set; }
}

And now just get the JSON String and create an object.

var jsonSerializer = new JavaScriptSerializer();

//i guess you kinda download the response from your php into a string or stream somehow.. i skipped this step
string jsonString = @"{""status"":45,""productIDs"":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]}";

myClass myObject = jsonSerializer.Deserialize<myClass>(jsonString);

Like others mentioned you can use a List for the ProductIDs. Depends on your Code, Style or .. whatever. Personally i would prefer a List.

Hope i could help.