0

A small program I am running will be creating 4 objects where each has data types like, bool array, strings, ints, etc, and all 4 classes are contained within a super class (for the purpose of making it one json string)

e.g.

public class Foo
{
    private A a;
    private B b;
    private C c;



}

public class A
{
    String str;
    int int_;
}

public class B
{
    boolean arr[];

}

public class C 
{
    // maybe an object, or rnum, or just priv data types
}

Now I can easily convert this into json use Gson library. my problem is sending this to a PHP page where it can decode the json and save the data from each object. Now I am new to PHP and from what I seen people say use

json_encode(); json_decode();

and which this I am wondering if this is the best/easiest way? from what I think i seen online, the decode will create an object but does that object match the java object to be exactly the same? is their a better way? Sorry for being a noob at this but any help is appreciated

Community
  • 1
  • 1
Tanner Summers
  • 689
  • 1
  • 8
  • 26

1 Answers1

1

The json_encode function will work for the PHP Object to Json conversion. You want to look into implementing the \JsonSerializable interface for that process. Going the other way is a little more complicated. The most direct approch is to use https://github.com/cweiske/jsonmapper. You could also json_decode to stdClass, use the php serializer to turn stdClass into a string, and then regex replace the class from \stdClass to the class you want. It's a bit hacky but it does work. See this post for an example.

Community
  • 1
  • 1
Alex Barker
  • 4,316
  • 4
  • 28
  • 47
  • thank you for the reply, so if i were to go from a java object that was turned into json and sent to my php webpage, convert that to an equivalent is not straight forward? so the way you suggested is that the best way in your opinion? – Tanner Summers Jun 24 '16 at 21:46
  • You need to create another object for it in your php code. That can be a php class or a stdClass or an array based "HashMap". Its totally up to what works for your implementation. PHP's json_decode can do arrays and stdClass just fine. If for some reason you need a PHP "POJO" to represent that request, you should probably use the jsonmapper project to map the values into your PHP "POJO". – Alex Barker Jun 24 '16 at 23:50
  • ok thank you, to finish up, what is the main difference between a PHP class and stdClass? and PHP POJO basically is making my own object correct? – Tanner Summers Jun 25 '16 at 00:07
  • stdClass is kind of like PHP's basic object type. You can just use it and dynamically add whatever properties you want to it. Creating your own PHP object representation is just more explicit and gives you the flexibility of implementing \jsonSerializable and other helper methods. It will depend on your need for your application. – Alex Barker Jun 27 '16 at 21:45