【问题标题】:How can I convert an object to a specific JSON format?如何将对象转换为特定的 JSON 格式?
【发布时间】:2017-04-18 14:55:51
【问题描述】:

json_encode 将对象转换为:

{
  "height":10,
  "width":20,
  "depth":5
}

但我还需要它包含对象类名:

{
  "cuboid":
  {
    "height":10,
    "width":20,
    "depth":5
  }
}

【问题讨论】:

标签: php json object


【解决方案1】:
public function toJson() {
    return json_encode([get_class($this) => $this]);
}

【讨论】:

    【解决方案2】:

    希望这对您有所帮助。在这里,我们将json 转换为array 并将其放入字段数组cuboid

    Try this code snippet here

    <?php
    
    ini_set('display_errors', 1);
    
    $json='{
      "height":10,
      "width":20,
      "depth":5
    }';
    $result["cuboid"]=json_decode($json,true);
    echo json_encode($result,JSON_PRETTY_PRINT);
    

    【讨论】:

      【解决方案3】:

      您可以使用get_class 获取对象的类名。

      $json = json_encode(array(get_class($object) => $object));
      

      【讨论】:

        【解决方案4】:

        json_encode 的规则

        • 如果你有一个对象,它将被编码为{'pro1':'value'}
        • 如果你有一个数组,它将被编码为['value']
        • 如果你有一个字符串,它将被编码为'value'

        注意:如果你在 php 中有一个 assoc-array,它就会变成 json 中的一个对象!如果你有一个索引数组,它将是一个 json 数组。 不要混合索引和关联!

        测试这个不好的做法:echo json_encode(array('foo' =&gt; 'bar',1,2)); 结果是这个不好的语法{"kitten":"test","0":1,"1":2}(属性名称不应该是数字!!!)

        因此,如果您想在属性名称下反对,请执行此操作

        $obj = new stdClass();
        $obj->prop = array(1,2,'a');
        $newObject = new stdClass();
        $newObject->objname = $obj;
        
        print_r(json_encode($newObject));
        

        变成:{'objname':{'prop':[1,2,'a']}}

        祝你有美好的一天:-)

        【讨论】:

          猜你喜欢
          • 2019-02-01
          • 2019-05-28
          • 1970-01-01
          • 2018-06-19
          • 1970-01-01
          • 2020-03-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多