`
sooxin
  • 浏览: 250745 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

使用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、
public static JSONObject getJSONObject(String str) {
        
if (str == null || str.trim().length() == 0) {
            
return null;
         }

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

        
return jsonObject;
}

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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics