GVKun编程网logo

php的数组和json格式的折腾(php 数组 json)

7

在这篇文章中,我们将带领您了解php的数组和json格式的折腾的全貌,包括php数组json的相关情况。同时,我们还将为您介绍有关161.使用fastjson将json格式的数据转化为对象、C#把li

在这篇文章中,我们将带领您了解php的数组和json格式的折腾的全貌,包括php 数组 json的相关情况。同时,我们还将为您介绍有关161.使用fastjson将json格式的数据转化为对象、C# 把list中的数据转成规定格式的json格式、JavaScript 如何处理 php 返回json格式的数据、JavaScript 如何处理 php 返回json格式的数据_PHP教程的知识,以帮助您更好地理解这个主题。

本文目录一览:

php的数组和json格式的折腾(php 数组 json)

php的数组和json格式的折腾(php 数组 json)

在PHP语言中使用JSON

日期: 2011年1月14日

目前,JSON已经成为最流行的数据交换格式之一,各大网站的API几乎都支持它。

我写过一篇《数据类型和JSON格式》,探讨它的设计思想。今天,我想总结一下PHP语言对它的支持,这是开发互联网应用程序(特别是编写API)必须了解的知识。

从5.2版本开始,PHP原生提供json_encode()和json_decode()函数,前者用于编码,后者用于解码。

一、json_encode()

该函数主要用来将数组和对象,转换为json格式。先看一个数组转换的例子:

  $arr = array (''a''=>1,''b''=>2,''c''=>3,''d''=>4,''e''=>5);  
  echo json_encode($arr);  

结果为

  {"a":1,"b":2,"c":3,"d":4,"e":5}  

再看一个对象转换的例子:

  $obj->body           = ''another post'';  
  $obj->id             = 21;  
  $obj->approved       = true;  
  $obj->favorite_count = 1;  
  $obj->status         = NULL;  
  echo json_encode($obj);  

结果为

  {    "body":"another post",  
    "id":21,  
    "approved":true,  
    "favorite_count":1,  
    "status":null  }   

由于json只接受utf-8编码的字符,所以json_encode()的参数必须是utf-8编码,否则会得到空字符或者null。当中文使用GB2312编码,或者外文使用ISO-8859-1编码的时候,这一点要特别注意。

二、索引数组和关联数组

PHP支持两种数组,一种是只保存"值"(value)的索引数组(indexed array),另一种是保存"名值对"(name/value)的关联数组(associative array)。

由于javascript不支持关联数组,所以json_encode()只将索引数组(indexed array)转为数组格式,而将关联数组(associative array)转为对象格式。

比如,现在有一个索引数组

  $arr = Array(''one'', ''two'', ''three'');  
  echo json_encode($arr);  

结果为:

  ["one","two","three"]   

如果将它改为关联数组:

  $arr = Array(''1''=>''one'', ''2''=>''two'', ''3''=>''three'');
   
  echo json_encode($arr);    

结果就变了:

  {"1":"one","2":"two","3":"three"}   

注意,数据格式从"[]"(数组)变成了"{}"(对象)。

如果你需要将"索引数组"强制转化成"对象",可以这样写

  json_encode( (object)$arr );  

或者

  json_encode ( $arr, JSON_FORCE_OBJECT );  

三、类(class)的转换

下面是一个PHP的类:

  class Foo {  
    const     ERROR_CODE = ''404'';  
    public    $public_ex = ''this is public'';  
    private   $private_ex = ''this is private!'';  
    protected $protected_ex = ''this should be protected''; 
   
    public function getErrorCode() {  
      return self::ERROR_CODE;  
    }  
  }  

现在,对这个类的实例进行json转换:

  $foo = new Foo;  
  $foo_json = json_encode($foo);  
  echo $foo_json;  

输出结果是

  {"public_ex":"this is public"}   

可以看到,除了公开变量(public),其他东西(常量、私有变量、方法等等)都遗失了。

四、json_decode()

该函数用于将json文本转换为相应的PHP数据结构。下面是一个例子:

  $json = ''{"foo": 12345}'';
   
  $obj = json_decode($json);  
  print $obj->{''foo''}; // 12345  

通常情况下,json_decode()总是返回一个PHP对象,而不是数组。比如:

  $json = ''{"a":1,"b":2,"c":3,"d":4,"e":5}'';
   
  var_dump(json_decode($json));  

结果就是生成一个PHP对象:

  object(stdClass)#1 (5) {  
    ["a"] => int(1)    ["b"] => int(2)    ["c"] => int(3)    ["d"] => int(4)    ["e"] => int(5)  
  }  

如果想要强制生成PHP关联数组,json_decode()需要加一个参数true:

  $json = ''{"a":1,"b":2,"c":3,"d":4,"e":5}'';
   
  var_dump(json_decode($json,true));  

结果就生成了一个关联数组:

  array(5) {  
     ["a"] => int(1)     ["b"] => int(2)     ["c"] => int(3)     ["d"] => int(4)     ["e"] => int(5)  
  }  

五、json_decode()的常见错误

下面三种json写法都是错的,你能看出错在哪里吗?

  $bad_json = "{ ''bar'': ''baz'' }";  
  $bad_json = ''{ bar: "baz" }'';  
  $bad_json = ''{ "bar": "baz", }'';  

对这三个字符串执行json_decode()都将返回null,并且报错。

第一个的错误是,json的分隔符(delimiter)只允许使用双引号,不能使用单引号。第二个的错误是,json名值对的"名"(冒号左边的部分),任何情况下都必须使用双引号。第三个的错误是,最后一个值之后不能添加逗号(trailing comma)。

另外,json只能用来表示对象(object)和数组(array),如果对一个字符串或数值使用json_decode(),将会返回null。

  var_dump(json_decode("Hello World")); //null  

六、参考材料

  [1] PHP Manual

  [2] Ed Finkler, JSON is Everybody''s Friend

(完)


161.使用fastjson将json格式的数据转化为对象

161.使用fastjson将json格式的数据转化为对象

1. 导入fastjson的jar包

        <!-- 9.fastjson -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.47</version>
            </dependency>

2. 常用几种类型的json转化为对象

 

 

2.1 对象形式的json

    @RequestMapping("/EasyJsonToObject.action")
    public void EasyJsonToObject(){
        
        //(1) 创建一个对象并将 给对象赋值 然后使用fastjson转化为json类型的数据   
            Student student = new  Student();
                    student.setId(UUID.randomUUID().toString().replaceAll("-", ""));//生成id
                    student.setName("张三");
                    student.setPassword("122455");
            String studentJson = JSON.toJSONString(student);//将对象转json
            System.out.println(studentJson);
                
            
        //(2)再将对象转化为
        Student changeStudent = JSON.parseObject(studentJson,Student.class);
        System.out.println(changeStudent);
    }

2.1.1 将对象转化为json

需要的实体类格式:

转换过程:

2.1.2 将json数据转为对象

2.2 将list对象转为json 然后将对象list数据

@RequestMapping("/listJsonToObject.action")
    public void listJsonToObject(){
        
        //(1) 创建一个对象并将 给对象赋值 然后使用fastjson转化为json类型的数据   
               List<Student> list= new ArrayList<Student>();
                Student student = new  Student();
                    student.setId(UUID.randomUUID().toString().replaceAll("-", ""));//生成id
                    student.setName("刘莹");
                    student.setPassword("123456");
               Student student2 = new  Student();
                    student2.setId(UUID.randomUUID().toString().replaceAll("-", ""));//生成id
                    student2.setName("张晓琪");
                    student2.setPassword("789456");
                    list.add(student);
                    list.add(student2);
            String studentJson = JSON.toJSONString(list);//将对象转json
            System.out.println(studentJson);
        
        
        //(2)再将对象转化为
        List<Student> list2 = JSON.parseArray(studentJson,Student.class);
        System.out.println(list2);
    }

 

需要的实体类对象

2.3  对象中含有对象 转化为对象

    @RequestMapping("/mapListJsonToObject.action")
    public void mapListJsonToObject(){
        
        //(1) 创建一个对象并将 给对象赋值 然后使用fastjson转化为json类型的数据   
        HashMap<String, Object> map = new   HashMap<String,Object>();//用来装数据
        
        Student student = new  Student();
            student.setId(UUID.randomUUID().toString().replaceAll("-", ""));//生成id
            student.setName("刘思佳");
            student.setPassword("123456");
        
            map.put("code", "200");
            map.put("data", student);
        String studentJson = JSON.toJSONString(map);//将对象转json
        System.out.println(studentJson);
        //(2)再将对象转化为
        Data data = JSON.parseObject(studentJson,Data.class);
        System.out.println(data);
    }

 

 

2.4 对象中含有list的json格式

    /**
     * 3.复杂json转为对象
     *                                        对象中包含数组的json
     * http://localhost:8080/mavenssm20180519//josnIncludeListJsonToObject.action
     * @Title: josnIncludeListJsonToObject
     * @Description: 
     * @return void
     * @throws 
       @date 2018年7月22日 下午10:46:00
     */
    @RequestMapping("/josnIncludeListJsonToObject.action")
    public void josnIncludeListJsonToObject(){
        //(1) 创建一个对象并将 给对象赋值 然后使用fastjson转化为json类型的数据   
        HashMap<String, Object> map = new   HashMap<String,Object>();//用来装数据
        
        List<Student> list= new ArrayList<Student>();
        Student student = new  Student();
            student.setId(UUID.randomUUID().toString().replaceAll("-", ""));//生成id
            student.setName("刘思佳");
            student.setPassword("123456");
        Student student2 = new  Student();
            student2.setId(UUID.randomUUID().toString().replaceAll("-", ""));//生成id
            student2.setName("陈晓莹");
            student2.setPassword("789456");
        list.add(student);
        list.add(student2);
            map.put("code", "200");
            map.put("data", list);
            String studentJson = JSON.toJSONString(map);//将对象转json
        System.out.println(studentJson);
        //(2)再将对象转化为
     Data data = JSON.parseObject(studentJson,Data.class);
        System.out.println(data);
    }

需要的实体类(****重要)

 将

C# 把list中的数据转成规定格式的json格式

C# 把list中的数据转成规定格式的json格式

前期编写xml解析器,需要把挑出来的个别数据调用web service接口传到mes系统。

功能那时已经实现,只是数据格式一直是不伦不类的状态。这次把数据格式搞定了。

model:

调用:

数据从list中取出放入数组:

数组元素逐个转换JObject对象:

最后整合成JArray对象:

最后的数据:

[
"{\"DateTime\":\"2018-10-08 08:44:32\",\"SampleNumber\":\"S18080629\",\"UserValue1\":\"10839\",\"TestMethod\":\"DS1000KG\",\"TestForce\":\"2246.00\",\"Max\":\"\",\"ValidForce\":\"1000g\"}",
"{\"DateTime\":\"2018-10-08 08:44:32\",\"SampleNumber\":\"S18080629\",\"UserValue1\":\"10839\",\"TestMethod\":\"DS1000KG\",\"TestForce\":\"2014.00\",\"Max\":\"\",\"ValidForce\":\"1000g\"}",
"{\"DateTime\":\"2018-10-08 08:44:32\",\"SampleNumber\":\"S18080629\",\"UserValue1\":\"10839\",\"TestMethod\":\"DS1000KG\",\"TestForce\":\"1634.00\",\"Max\":\"\",\"ValidForce\":\"1000g\"}"
]

 

 这次算是把之前想用但是一直不知道怎么下手的JSon用上了,但是还是一个小白。

 

JavaScript 如何处理 php 返回json格式的数据

JavaScript 如何处理 php 返回json格式的数据

javascript 如何处理 php 返回json格式的数据,下面我们通过一个示例来说明!

假设php返回如下一个数组:

$arr = array(
	array(
		''name''=&gt;''qianyuqianxun'',
		''nick''=&gt;''千与千寻'',
		''contact''=&gt;array(
			''website''=&gt;''http://www.phpernote.com''
		)
	),
	array(
		''name''=&gt;''qisha'',
		''nick''=&gt;''七煞'',
		''email''=&gt;''yhm.1234@163.com'',
		''contact''=&gt;array(
			''website''=&gt;''http://www.baidu.com''
		)
	)
);
print_r(json_encode($arr));
exit;
登录后复制

则客户端JS可如下调用以上返回的数据:

$(document).ready(function(){
	var url=''http://www.phpernote.com/json.php''
	$(''#submitBtn'').click(function(){
		$.post(url,'''',function(msg){
			var myObject=eval(''(''+msg+'')'');//msg为返回的类型为字符串,转化为json对象
			var str='''';
			var len=myObject.length;
			for(i=0;i<len str><td>''+myObject[i].name+''</td>
<td>''+myObject[i].nick+''</td>
<td>''+myObject[i].contact.website+''</td>'';
			}
			$(''#feedbackTable'').html(str);
		})
	})
})</len>
登录后复制

您可能感兴趣的文章

  • jquery如何处理json数据
  • PHP数字格式化,数字每三位加逗号
  • mysql 队列实现高效并发读数据
  • jquery+html+php 实现Ajax无刷新文件上传
  • 合理使用MySQL数据库索引以使数据库高效运行
  • 在php中分别使用curl的post提交数据的方法和get获取网页数据的方法总结
  • php获取某段时间内每个月的方法,返回由这些月份组成的数组
  • PHP连接access数据库的二种方法

JavaScript 如何处理 php 返回json格式的数据_PHP教程

JavaScript 如何处理 php 返回json格式的数据_PHP教程

javascript 如何处理 php 返回json格式的数据,下面我们通过一个示例来说明!

假设php返回如下一个数组:

$arr = array(
	array(
		''name''=&gt;''qianyuqianxun'',
		''nick''=&gt;''千与千寻'',
		''contact''=&gt;array(
			''website''=&gt;''http://www.phpernote.com''
		)
	),
	array(
		''name''=&gt;''qisha'',
		''nick''=&gt;''七煞'',
		''email''=&gt;''yhm.1234@163.com'',
		''contact''=&gt;array(
			''website''=&gt;''http://www.baidu.com''
		)
	)
);
print_r(json_encode($arr));
exit;
登录后复制

则客户端JS可如下调用以上返回的数据:

$(document).ready(function(){
	var url=''http://www.phpernote.com/json.php''
	$(''#submitBtn'').click(function(){
		$.post(url,'''',function(msg){
			var myObject=eval(''(''+msg+'')'');//msg为返回的类型为字符串,转化为json对象
			var str='''';
			var len=myObject.length;
			for(i=0;i<len str><td>''+myObject[i].name+''</td>
<td>''+myObject[i].nick+''</td>
<td>''+myObject[i].contact.website+''</td>'';
			}
			$(''#feedbackTable'').html(str);
		})
	})
})</len>
登录后复制

您可能感兴趣的文章

  • jquery如何处理json数据
  • PHP数字格式化,数字每三位加逗号
  • mysql 队列实现高效并发读数据
  • jquery+html+php 实现Ajax无刷新文件上传
  • 合理使用MySQL数据库索引以使数据库高效运行
  • 在php中分别使用curl的post提交数据的方法和get获取网页数据的方法总结
  • php获取某段时间内每个月的方法,返回由这些月份组成的数组
  • PHP连接access数据库的二种方法

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/764170.htmlTechArticleJavaScript 如何处理 php 返回json格式的数据,下面我们通过一个示例来说明! 假设php返回如下一个数组: $arr = array(array(''name''=''qianyuqianxun'',''n...

今天关于php的数组和json格式的折腾php 数组 json的讲解已经结束,谢谢您的阅读,如果想了解更多关于161.使用fastjson将json格式的数据转化为对象、C# 把list中的数据转成规定格式的json格式、JavaScript 如何处理 php 返回json格式的数据、JavaScript 如何处理 php 返回json格式的数据_PHP教程的相关知识,请在本站搜索。

本文标签: