close

驗證是否為JSON格式:
http://jsonlint.com/

利用JAVA直接抓取JSON格式範例如下:

package com.example;

import net.sf.json.JSONObject;

public class Test {
	
	public static void main(String []args){
		String tmp= "{\"Data\":{\"Name\":\"MichaelChan\",\"Email\":\"XXXX@XXX.com\",\"Phone\":[02-12345678,0911123456]}}";
		JSONObject json = JSONObject.fromObject(tmp);
		System.out.println(json.get("Data"));
		System.out.println(((JSONObject)json.get("Data")).get("Name")); // MichaelChan
		System.out.println(((JSONObject)json.get("Data")).get("Email")); // XXXX@XXX.com
		System.out.println(((JSONObject)json.get("Data")).getJSONArray("Phone").get(0)); //02-12345678
		
	}
}

利用JAVA透過URL直接抓取JSON格式範例如下:

package com.example;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import net.sf.json.JSONObject;

public class Test2 {
     public static void main(String[] args) throws Exception {
         String url = "http://192.168.1.106:8080/test/test.json";
         InputStream is = new URL(url).openStream();
         try {
              BufferedReader rd = new BufferedReader(new InputStreamReader(is,"utf-8")); //避免中文亂碼問題
              StringBuilder sb = new StringBuilder();
              int cp;
              while ((cp = rd.read()) != -1) {
                  sb.append((char) cp);
              }
              JSONObject json = JSONObject.fromObject(sb.toString());
              System.out.println(json.get("hello"));
         } finally {
              is.close();
         }
     }
}

test.json

{"hello":[{
   "otherkey": "othervalue",
   "key": "value"
},{
	"otherkey": "othervalue2",
   "key": "value2"
}]}
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Codeless 的頭像
    Codeless

    Codeless的部落格

    Codeless 發表在 痞客邦 留言(0) 人氣()