使用Java操作JSON字串對象

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.