在Java中解析與構造JSON

來源:互聯網
上載者:User

在www.json.org上公布了很多Java下的json解析工具,其中org.json和json-lib比較簡單,兩者使用上差不多。下面兩段原始碼是分別使用這兩個工具解析和構造JSON的示範程式。
這是使用json-lib的程式:
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

public class Test {

    public static void main(String[] args) {
        String json = "{\"name\":\"reiz\"}";
        JSONObject jsonObj = JSONObject.fromObject(json);
        String name = jsonObj.getString("name");
      
        jsonObj.put("initial", name.substring(0, 1).toUpperCase());

        String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" };
        jsonObj.put("likes", likes);

        Map<String, String> ingredients = new HashMap<String, String>();
        ingredients.put("apples", "3kg");
        ingredients.put("sugar", "1kg");
        ingredients.put("pastry", "2.4kg");
        ingredients.put("bestEaten", "outdoors");
        jsonObj.put("ingredients",ingredients);
      
        System.out.println(jsonObj);
    }
}
這是使用org.json的程式:
import java.util.HashMap;
import java.util.Map;

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

public class Test {

    public static void main(String[] args) throws JSONException {
        String json = "{\"name\":\"reiz\"}";
        JSONObject jsonObj = new JSONObject(json);
        String name = jsonObj.getString("name");

        jsonObj.put("initial", name.substring(0, 1).toUpperCase());

        String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" };
        jsonObj.put("likes", likes);

        Map<String, String> ingredients = new HashMap<String, String>();
        ingredients.put("apples", "3kg");
        ingredients.put("sugar", "1kg");
        ingredients.put("pastry", "2.4kg");
        ingredients.put("bestEaten", "outdoors");
        jsonObj.put("ingredients", ingredients);
        System.out.println(jsonObj);

        System.out.println(jsonObj);
    }
}
兩者的使用幾乎是相同的,但org.json比json-lib要輕量得多,前者沒有任何依賴,而後者要依賴ezmorph和commons的lang、logging、beanutils、collections等組件。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.