json 간단한 사용

5973 단어 json
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class test_main {

    static void parseJson() throws JSONException {
        String result = "[{\"username\": \"your name\", \"user_json\": {\"username\": \"your name\", \"nickname\": \"your nickname\"}}]";
        JSONArray resultArray = new JSONArray(result);
        JSONObject resultObj = resultArray.optJSONObject(0);

        String username = resultObj.getString("username");

        System.out.println(username);

        JSONObject user = resultObj.getJSONObject("user_json");
        String nickname = user.getString("nickname");
        System.out.println(nickname);

    }

    static void stringToJosn() throws JSONException {
        //   JSONObject  
        JSONObject json = new JSONObject();

        //  json     
        json.put("username", "wanglihong");
        json.put("height", 12.5);
        json.put("age", 24);

        //   JSONArray  ,  json     
        JSONArray array = new JSONArray();
        array.put(json);

        //       
        String jsonStr = array.toString();

        System.out.println(jsonStr);

    }

    static void setToJosn() throws JSONException {
        //    ArrayList       
        List<String> list = new ArrayList<String>();
        list.add("username");
        list.add("age");
        list.add("sex");

        //    HashMap       
        Map map = new HashMap();
        map.put("bookname", "CSS3  ");
        map.put("price", 69.0);

        //    JSONArray  ,     
        JSONArray array = new JSONArray();
        array.put(list);
        array.put(map);
        
        
        String jsonStr = array.toString();

        System.out.println(jsonStr);
        //    JSON    :[["username","age","sex"],{"price":69,"bookname":"CSS3  "}]

    }

    public static void main(String[] args) throws JSONException {
        // TODO Auto-generated method stub

        // parseJson();

        // stringToJosn();
        setToJosn();
    }

}

참조:http://www.cnblogs.com/undead/archive/2012/07/18/2594900.html

좋은 웹페이지 즐겨찾기