json_decode to custom class

json_decode laravel
json_decode recursive
php7 json_decode
json_decode string
json_decode null
php json mapper
json_decode not working
php json_decode utf8

Is it possible to decode a json string to an object other than stdClass?

Not automatically. But you can do it the old fashioned route.

$data = json_decode($json, true);

$class = new Whatever();
foreach ($data as $key => $value) $class->{$key} = $value;

Or alternatively, you could make that more automatic:

class Whatever {
    public function set($data) {
        foreach ($data AS $key => $value) $this->{$key} = $value;
    }
}

$class = new Whatever();
$class->set($data);

Edit: getting a little fancier:

class JSONObject {
    public function __construct($json = false) {
        if ($json) $this->set(json_decode($json, true));
    }

    public function set($data) {
        foreach ($data AS $key => $value) {
            if (is_array($value)) {
                $sub = new JSONObject;
                $sub->set($value);
                $value = $sub;
            }
            $this->{$key} = $value;
        }
    }
}

// These next steps aren't necessary. I'm just prepping test data.
$data = array(
    "this" => "that",
    "what" => "who",
    "how" => "dy",
    "multi" => array(
        "more" => "stuff"
    )
);
$jsonString = json_encode($data);

// Here's the sweetness.
$class = new JSONObject($jsonString);
print_r($class);

From JSON to model instances in PHP, For example I'm trying to encode/decode a class called Person . I need to decode JSON data. json_decode returns the decoded data in an  I think the complex number example of non serializable, custom type encoding/decoding wasn’t the best choice. Went from a very useful/trivial example using JSON from API’s straight to a non trivial use case.

We built JsonMapper to map JSON objects onto our own model classes automatically. It works fine with nested/child objects.

It only relies on docblock type information for mapping, which most class properties have anyway:

<?php
$mapper = new JsonMapper();
$contactObject = $mapper->map(
    json_decode(file_get_contents('http://example.org/contact.json')),
    new Contact()
);
?>

json_decode to custom class, Not automatically. But you can do it the old fashioned route. $data = json_decode​($json, true); $class = new Whatever(); foreach ($data as $key  Now you could first do encoding from json to class RootObject, and then create MyRootObject based on it: string path = @"D:\test.txt"; var r = new StreamReader(path); var myJson = r.ReadToEnd(); RootObject root = Json.Decode<RootObject>(myJson); MyRootObject myroot = new MyRootObject(root);

You can do it - it's a kludge but totally possible. We had to do when we started storing things in couchbase.

$stdobj = json_decode($json_encoded_myClassInstance);  //JSON to stdClass
$temp = serialize($stdobj);                   //stdClass to serialized

// Now we reach in and change the class of the serialized object
$temp = preg_replace('@^O:8:"stdClass":@','O:7:"MyClass":',$temp);

// Unserialize and walk away like nothing happend
$myClassInstance = unserialize($temp);   // Presto a php Class 

In our benchmarks this was way faster than trying to iterate through all the class variables.

Caveat: Won't work for nested objects other than stdClass

Edit: keep in mind the data source, it's strongly recommended that you don't do this withe untrusted data from users without a very carful analysis of the risks.

json_decode to custom class, Not automatically. But you can do it the old fashioned route. $data = json_decode​($json, true); $class = new Whatever(); foreach ($data as $key  Now you could first do encoding from json to class RootObject, and then create MyRootObject based on it: string path = @"D:\test.txt"; var r = new StreamReader(path); var myJson = r.ReadToEnd(); RootObject root = Json.Decode<RootObject>(myJson); MyRootObject myroot = new MyRootObject(root);

You could use Johannes Schmitt's Serializer library.

$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$object = $serializer->deserialize($jsonData, 'MyNamespace\MyObject', 'json');

In the latest version of the JMS serializer the syntax is:

$serializer = SerializerBuilder::create()->build();
$object = $serializer->deserialize($jsonData, MyObject::class, 'json');

Deserializing JSON into Objects in PHP - Homullus, I was wondering, if json_decode serializes a multidimensional JSON into a stdClass, why can't it serialize into a specified custom Class? The data package is a JSON object. Assume the JSON Company Object is formatted to exactly match the Company Class that the API uses. How do I get the JSON Company Object data into the Company Class? It seems silly to instantiate a Company Object, json_decode() the JSON Object, then call dozens of set() methods.

You can make a wrapper for your object and make the wrapper look like it is the object itself. And it will work with multilevel objects.

<?php
class Obj
{
    public $slave;

    public function __get($key) {
        return property_exists ( $this->slave ,  $key ) ? $this->slave->{$key} : null;
    }

    public function __construct(stdClass $slave)
    {
        $this->slave = $slave;
    }
}

$std = json_decode('{"s3":{"s2":{"s1":777}}}');

$o = new Obj($std);

echo $o->s3->s2->s1; // you will have 777

JsonSerializable::jsonSerialize - Manual, Example #2 JsonSerializable::jsonSerialize() example returning an associative array. <?php class ArrayValue implements JsonSerializable { public function  To solve this, we need to build a custom encoder to make our Class JSON serializable. There are multiple ways to Make a Python Class JSON Serializable. You can pick the one which best suited to your problem complexity. Let’ understand each one-by-one.

json_decode - Manual, json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $​options = 0 ]]] ) : mixed. Takes a JSON encoded string and converts it into a PHP​  To use a custom JSON property naming policy, create a class that derives from JsonNamingPolicy and override the ConvertName method, as shown in the following example: using System.Text.Json; namespace SystemTextJsonSamples { public class UpperCaseNamingPolicy : JsonNamingPolicy { public override string ConvertName(string name) => name.ToUpper(); } }

cweiske/jsonmapper: Map nested JSON structures onto PHP classes, Starting from a base object, it maps JSON data on class properties, converting them into the correct simple types or objects. It's a bit like the native SOAP parameter  JSON is the format I use the most when it comes to data transfer. In almost every case I serialize my date with json_encode and at some point in time I use json_decode to get the data back into a somehow structured format. For example I'm trying to encode/decode a class called Person.

JSON DECODE(), The JSON_DECODE() function is used to create a dynamic array (object) from the JSON formatted string, <expC>. Example. myobj =  json_decode to custom class (7) As Gordon says is not possible. But if you are looking for a way to obtain a string that can be decoded as an instance of a give class you can use serialize and unserialize instead.

Comments
  • Nothing new on this after so many years?
  • I like you suggestions, just to remark that it won't work with nested objects (other than STDClass or the converted object)
  • WOW! That's just amazing.
  • Can you explain the OSL3 license? If I use JsonMapper on a website, must I release the source code of that website? If I use JsonMapper in code on a device I sell, must all of that device's code be open source?
  • No, you only have to publish the changes you do to JsonMapper itself.
  • Does this work with encapsulated subclasses. E.g. { "a": {"b":"c"} }, where the object in a is of another class and not just an associative array?
  • no, json_decode creates stdclass objects, including sub objects, if you want to have them be anything else you have to kludge each object as above.
  • Thank you, that's what I imagined
  • How about usig this solution on objects where the constructor has parameters. I can't get it to work. I was hoping someone could point me in the right direction to make this solution work with an object that has a custom constructor with parameters.
  • I went ahead and built this into a function. Note that it still doesn't work with subclasses. gist.github.com/sixpeteunder/2bec86208775f131ce686d42f18d8621
  • The syntax is not dependent on JMS Serializer version, but rather on PHP version - starting from PHP5.5 you can use ::class notation: php.net/manual/en/…
  • This does not seem to address the question. If it does, you have to provide some explanation.
  • This may be true, but the question isn't asking about representing objects in a generic way. It sounds like he's got a specific JSON bag that maps to a specific class on one or both ends. There's no reason you can't use JSON as an explicit serialization of non-generic named classes in this way. Naming it as you're doing is fine if you want a generic solution, but there's also nothing wrong with having an agreed upon contract on the JSON structure.
  • This could work if you implement Serializable on the encoding end, and have conditionals on the decoding end. Could even work with subclasses if organized properly.