yabovip

举个栗子

java中如何使用json,C#中如何使用json,php中如何使用json,javascript如何使用json

yabovipJSONSHIYIZHONGQUDAIXMLDESHUJUJIEGOU,HExmlXIANGBI,TAGENGXIAOQIAODANMIAOSHUNENGLIQUEBUCHA,YOUYUTADEXIAOQIAOSUOYIWANGLUOCHUANSHUSHUJUJIANGJIANSHAOGENGDUOLIULIANGCONGERJIAKUAISUDU,

那么,JSON到底是什么?yabovipJSONyabovipJSONP

Javascrip操作json方法

var str1 = '{ "name": "cxh", "sex": "man" }';

var data=;//转换为json对象//data =(new

alert (data.name);//会显示出cxh

yabovipBUGUOevalJIEXIjsonYOUANQUANYINHUAN!

XIANZAIDADUOSHULIULANQI(IE8JIYISHANG,ChromeHEFirefoxCHABUDUOQUANBU)ZIDAIYUANSHENGJSONDUIXIANG,TIGONGJSON.parse()FANGFAJIEXIJSON,TIGONGJSON.stringify()FANGFASHENGCHENGJSON,QINGSHIYONGZHEILIANGGEFANGFA!

RUGUODANXINparse()DUIDUIXIANGPAOYICHANG,KEYIJIAYIGEFENGZHUANGHANSHU:

JSON.pParse = function( tar ) {

    if( typeof( tar ) === 'string' ) {

        return JSON.parse( tar );

    } else {

        return tar;

    }

};

GANXIEoschinaDE WOTUBIE TIGONGXIUGAIFANGFA。

json.js操作json方法

yabovip    WEILEFANGBIANDICHULIJSONSHUJU,JSONTIGONGLEjson.jsBAO,XIAZAIDIZHI:

    ZAISHUJUCHUANSHULIUCHENGZHONG,jsonSHIYIWENBEN,JIZIFUCHUANDEXINGSHICHUANDIDE,ERJSCAOZUODESHIJSONDUIXIANG,SUOYI,JSONDUIXIANGHEJSONZIFUCHUANZHIJIANDEXIANGHUZHUANHUANSHIGUANJIAN。LIRU:

    JSONZIFUCHUAN:

    var str1 = '{ "name": "cxh", "sex": "man" }';

yabovip    JSONDUIXIANG:

yabovip    var str2 = { "name": "cxh", "sex": "man" };

yabovip    YI、JSONZIFUCHUANZHUANHUANWEIJSONDUIXIANG

    YAOYUNYONGSHANGMIANDEstr1,BIXUYUNYONGXIAMIANDEYAOLINGXIANZHUANHUAWEIJSONDUIXIANG:

    //YOUJSONZIFUCHUANZHUANHUANWEIJSONDUIXIANG

    var obj = ;

HUOZHE

    var obj = str.parseJSON(); //YOUJSONZIFUCHUANZHUANHUANWEIJSONDUIXIANG

    HUOZHE

    var obj = JSON.parse(str); //YOUJSONZIFUCHUANZHUANHUANWEIJSONDUIXIANG

    RANHOU,JIUKEYIZHEIYANGDUQU:

    Alert(obj.name);

    Alert(obj.sex);

    TEBIELIUXIN: RUGUOobjBENLAIJIUSHIYIGEJSONDUIXIANG,NEIMEYUNYONG eval()HANSHUZHUANHUANHOU(NAPASHIDUOCIZHUANHUAN)HAISHIJSONDUIXIANG,DANSHIYUNYONG parseJSON()HANSHUCHULIHOUHUIYOUYIWEN(PAOCHUYUFAYICHANG)。

    ER、KEYIYUNYONG toJSONString()HUOZHEQUANJUYAOLING JSON.stringify()JIANGJSONDUIXIANGZHUANHUAWEIJSONZIFUCHUAN。

yabovip    LIRU:

yabovip    var last=obj.toJSONString(); //JIANGJSONDUIXIANGZHUANHUAWEIJSONZIFU

yabovip    HUOZHE

yabovip    var last=JSON.stringify(obj); //JIANGJSONDUIXIANGZHUANHUAWEIJSONZIFU

    alert(last);

yabovip    LIUXIN:

    SHANGMIANDEDUOGEYAOLINGZHONG,CHULEHANSHUSHIjsZIDAIDEZHIWAI,QITADEDUOGEYAOLINGDOULAIZIjson.jsBAO。XINBANBENDE JSON XIUGAILE API,JIANG JSON.stringify() HE JSON.parse() LIANGGEYAOLINGDOUZHURUDAOLE Javascript DENEIJIANDUIXIANGLIMIAN,QIANZHEBIANCHENGLE Object.toJSONString(),ERHOUZHEBIANCHENGLE String.parseJSON()。RUGUOTISHIZHAOBUDAOtoJSONString()HEparseJSON()YAOLING,ZESHUOMINGNINDEjsonBAOBANBENTAIDI。

JQuery获取json方法

YUFA

jQuery.getJSON(url,data,success(data,status,xhr))

CANSHU

参数 描述
url 必需。规定将请求发送的哪个 URL。
data 可选。规定连同请求发送到服务器的数据。
success(data,status,xhr)

yabovipKEXUAN。GUIDINGDANGQINGQIUCHENGGONGSHIYUNXINGDEHANSHU。

EWAIDECANSHU:

  • response - 包含来自请求的结果数据
  • status - 包含请求的状态
  • xhr - 包含 XMLHttpRequest 对象

YONGLI

$.getJSON("test.js", function(json){ alert("JSON Data: " + json.users[3].name); });

Java操作json方法

yabovipZHEIGEXUYAOjson-lib.jarBAOZHICHI GAIjarXIAZAIDIZHI:

//JSON对象 JSONObject的使用

        String str1 = "{ 'name': 'cxh', 'sex': '1' }";

        JSONObject obj = JSONObject.fromObject(str1);

        String name = obj.getString("name"); //直接返回字符串型 cxh

        Object nameo = obj.get("name"); //直接返回对象型的cxh

        int age = obj.getInt("sex"); //直接返回int型的sex

        

        //JSON数组对象 JSONArray的运用

        String jsonArrStr = "[{ 'name': 'cxh', 'sex': '1','website':'http://zionmax.com' },{ 'name': '三少', 'sex': '1','website':'http://zionmax.com' }]";

        JSONArray array = JSONArray.fromObject(jsonArrStr);

        int size = array.size(); //获取JSON数组大小

        JSONObject jo = array.getJSONObject(0);//取第一个JSON对象

        for(int i=0;i<size;i++){

            JSONObject jo1 = array.getJSONObject(i);

            System.out.println(jo1.getString("website")); //循环返回网址

        }

        

        //序列化Bean对象为JSON对象

        User user = new User();

        user.setName("cxh");

        user.setSex(1);

        user.setWebsite("http://zionmax.com");

        JSONObject jo2 =  JSONObject.fromObject(user);

        System.out.println(jo2.toString()); //则会输出 { 'name': 'cxh', 'sex': '1','website':'http://zionmax.com' }

 

Php

 一、json_encode()

  GAIHANSHUZHUYAOYONGLAIJIANGSHUZUHEDUIXIANG,ZHUANHUANWEIjsonGESHI。XIANKANYIGESHUZUZHUANHUANDELIZI:

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

yabovipecho json_encode($arr);

  JIEGUOWEI

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

  ZAIKANYIGEDUIXIANGZHUANHUANDELIZI:

$obj->body = 'another post';

yabovip$obj->id = 21;

yabovip$obj->approved = true;

yabovip$obj->favorite_count = 1;

yabovip$obj->status = NULL;

echo json_encode($obj);

  JIEGUOWEI

{
yabovip    "body":"another post",

"id":21,

yabovip"approved":true,

yabovip"favorite_count":1,

"status":null
  }

yabovip  YOUYUjsonZHIJIESHOUutf-8BIANMADEZIFU,SUOYIjson_encode()DECANSHUBIXUSHIutf-8BIANMA,FOUZEHUIDEDAOKONGZIFUHUOZHEnull。DANGZHONGWENSHIYONGGB2312BIANMA,HUOZHEWAIWENSHIYONGISO-8859-1BIANMADESHIHOU,ZHEIYIDIANYAOTEBIEZHUYI。

  二、索引数组和关联数组

  PHPZHICHILIANGZHONGSHUZU,YIZHONGSHIZHIBAOCUN"ZHI"(value)DESUOYINSHUZU(indexed array),LINGYIZHONGSHIBAOCUN"MINGZHIDUI"(name/value)DEGUANLIANSHUZU(associative array)。

  YOUYUjavascriptBUZHICHIGUANLIANSHUZU,SUOYIjson_encode()ZHIJIANGSUOYINSHUZU(indexed array)ZHUANWEISHUZUGESHI,ERJIANGGUANLIANSHUZU(associative array)ZHUANWEIDUIXIANGGESHI。

yabovip  BIRU,XIANZAIYOUYIGESUOYINSHUZU

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

echo json_encode($arr);

  JIEGUOWEI:

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

yabovip  RUGUOJIANGTAGAIWEIGUANLIANSHUZU:

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

echo json_encode($arr);

  JIEGUOJIUBIANLE:

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

yabovip  ZHUYI,SHUJUGESHICONG"[]"(SHUZU)BIANCHENGLE"{}"(DUIXIANG)。

yabovip  RUGUONIXUYAOJIANG"SUOYINSHUZU"QIANGZHIZHUANHUACHENG"DUIXIANG",KEYIZHEIYANGXIE

yabovipjson_encode( (object)$arr );

  HUOZHE

yabovipjson_encode ( $arr, JSON_FORCE_OBJECT );

  三、类(class)的转换

yabovip  XIAMIANSHIYIGEPHPDELEI:

class Foo {

yabovipconst ERROR_CODE = '404';

yabovippublic $public_ex = 'this is public';

yabovipprivate $private_ex = 'this is private!';

protected $protected_ex = 'this should be protected';

yabovippublic function getErrorCode() {

return self::ERROR_CODE;

}

}

  XIANZAI,DUIZHEIGELEIDESHILIJINXINGjsonZHUANHUAN:

yabovip$foo = new Foo;

yabovip$foo_json = json_encode($foo);

echo $foo_json;

  SHUCHUJIEGUOSHI

{"public_ex":"this is public"}

  KEYIKANDAO,CHULEGONGKAIBIANLIANG(public),QITADONGXI(CHANGLIANG、SIYOUBIANLIANG、FANGFADENGDENG)DOUYISHILE。

  四、json_decode()

  GAIHANSHUYONGYUJIANGjsonWENBENZHUANHUANWEIXIANGYINGDEPHPSHUJUJIEGOU。XIAMIANSHIYIGELIZI:

$json = '{"foo": 12345}';

$obj = json_decode($json);

yabovipprint $obj->{'foo'}; // 12345

yabovip  TONGCHANGQINGKUANGXIA,json_decode()ZONGSHIFANHUIYIGEPHPDUIXIANG,ERBUSHISHUZU。BIRU:

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

yabovipvar_dump(json_decode($json));

yabovip  JIEGUOJIUSHISHENGCHENGYIGEPHPDUIXIANG:

object(stdClass)#1 (5) {

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

}

  RUGUOXIANGYAOQIANGZHISHENGCHENGPHPGUANLIANSHUZU,json_decode()XUYAOJIAYIGECANSHUtrue:

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

var_dump(json_decode($json,true));

  JIEGUOJIUSHENGCHENGLEYIGEGUANLIANSHUZU:

array(5) {

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

}

  五、json_decode()的常见错误

  XIAMIANSANZHONGjsonXIEFADOUSHICUODE,NINENGKANCHUCUOZAINALIMA?

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

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

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

  DUIZHEISANGEZIFUCHUANZHIXINGjson_decode()DOUJIANGFANHUInull,BINGQIEBAOCUO。

  DIYIGEDECUOWUSHI,jsonDEFENGEFU(delimiter)ZHIYUNXUSHIYONGSHUANGYINHAO,BUNENGSHIYONGDANYINHAO。DIERGEDECUOWUSHI,jsonMINGZHIDUIDE"MING"(MAOHAOZUOBIANDEBUFEN),RENHEQINGKUANGXIADOUBIXUSHIYONGSHUANGYINHAO。DISANGEDECUOWUSHI,ZUIHOUYIGEZHIZHIHOUBUNENGTIANJIADOUHAO(trailing comma)。

yabovip  LINGWAI,jsonZHINENGYONGLAIBIAOSHIDUIXIANG(object)HESHUZU(array),RUGUODUIYIGEZIFUCHUANHUOSHUZHISHIYONGjson_decode(),JIANGHUIFANHUInull。

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

其他

yabovipQITADE YOUYUWOBUHUI,SUOYIZHINENGSHIDAIBUCHONG,RUGUOHUIDE QINGBADAIMAHESUOXUYAODEZHICHIKUFASONGDAOWODEYOUXIANG ,BEICAIYONGDEKEYIJIASHANGNINDEWANGZHANWAILIANE。

Python(谢谢【张东桂】提供的代码)

import json

str1 = '{ "name": "cxh", "sex": "1" }'
# 或者
# str1 = """{ "name": "cxh", "sex": "1" }"""
# 或者
# str1 = "{ \"name\": \"cxh\", \"sex\": \"1\" }"

obj = json.loads(str1)
print(obj["name"])
print(obj["sex"])

# 由于出现中文,记得文件头加入 # coding:utf8
json_arr_str = """[{ "name": "cxh", "sex": "1","website":"http://zionmax.com" },{ "name": "我的", "sex": "1","website":"http://zionmax.com" }]"""

arr = json.loads(json_arr_str)

for o in arr:
    print(o["name"])
    print(o["sex"])
    print(o["website"])

				

C#(谢谢【黄明辉】提供的代码)

需要的dll:Newtonsoft.Json.dll,
	//读取简单的json
string json="{\"username\":\"张三\"}";
string username = string.Empty;
JObject jObj=JObject.Parse(json); //进行格式化
username = jObj["username"].ToString();
Console.WriteLine(username);


//读取嵌套对象的json
json = "{\"username\":\"张三\",data:{\"address\":\"福建厦门\"}}";
jObj = JObject.Parse(json);
string address = string.Empty;
address = jObj["data"]["address"].ToString();
Console.WriteLine(address);

//读取数组,操作方式与数组类似
json = "{\"username\":\"张三\",data:[{\"address\":\"福建厦门\"},{\"address\":\"福建福州\"}]}";
jObj = JObject.Parse(json);
 address = string.Empty;
address = jObj["data"][0]["address"].ToString()+","+ jObj["data"][1]["address"].ToString();
Console.WriteLine(address);

Console.ReadLine();
				

Objective-C(谢谢【张万平】提供的代码)

//JSON字符串转字典:

NSString *str1 = @"{\"name\":\"cxh\",\"sex\":\"1\"}";
NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
NSError *error1;
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:&error1];
/*
 NSJSONReadingMutableContainers 创建结果为可变数组/字典
 NSJSONReadingMutableLeaves 创建结果中字符串是可变字符串
 NSJSONReadingAllowFragments 允许json最外层不是数组或字典
 */
if (!error1) {
	NSLog(@"jsonDic is:%@",jsonDic);
}
else{
	NSLog(@"error:%@",error1);
}

//字典转JSON字符串
NSError *error2 = nil;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:&error2];
if (!error2) {
	NSString *str2 = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
	NSLog(@"json string is:%@",str2);
}
else{
	NSLog(@"error:%@",error2);
}
				
yabovip 博电竞 泛亚体育 泛亚体育 龙虎28 博亚平台 博亚平台