使用Java操作JSON字符串对象

1、如果我们需要实现一个配置管理的功能,那么为每个配置项目增加一个字段既复杂也不利于扩展,所以我们通常使用一个字符串来保存配置项目信息,这里介绍如何使用json的字符串解析来达到刚才说的目的。引入Json需要的类库:

import  org.json.JSONException;   
import  org.json.JSONObject;  


2、生成一个json对象(可以添加不同类型的数据):

JSONObject jsonObject  =   new  JSONObject();
jsonObject.put(
" a " 1 );   jsonObject.put( " b " 1.1 );
jsonObject.put(
" c " 1L );
jsonObject.put(
" d " " test " );
jsonObject.put(
" e " true );
System.out.println(jsonObject);
// {"d":"test","e":true,"b":1.1,"c":1,"a":1}  

 


3、解析一个json对象(可以解析不同类型的数据),getJSONObject(String str):

jsonObject  =  getJSONObject( " {d:test,e:true,b:1.1,c:1,a:1} " );
System.out.println(jsonObject);
// {"d":"test","e":true,"b":1.1,"c":1,"a":1}
System.out.println(jsonObject.getInt( " a " ));
System.out.println(jsonObject.getDouble(
" b " ));
System.out.println(jsonObject.getLong(
" c " ));
System.out.println(jsonObject.getString(
" d " ));
System.out.println(jsonObject.getBoolean(
" e " ));


4、

ExpandedBlockStart.gif ContractedBlock.gif public   static  JSONObject getJSONObject(String str)  {
ExpandedSubBlockStart.gifContractedSubBlock.gif        
if (str == null || str.trim().length() == 0{
            
return null;
        }

        JSONObject jsonObject 
= null;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try {
            jsonObject 
= new JSONObject(str);
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (JSONException e) {
            e.printStackTrace(System.err);
        }

        
return jsonObject;
    }

 

包下载地址:http://www.json.org/java/index.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值