簡體   English   中英

使用jsonparser解析API URL中的json數據

[英]parsing json data in API url using jsonparser

我在此URL有一個JSON數據: http : //api.pemiluapi.org/calonpresiden/api/caleg/jk?apiKey=56513c05217f73e6be82d5542368ae4f

當我嘗試使用此jsonparser代碼進行解析時:

    package percobaan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public String makeHttpRequest(String url, String method) {
        return this.makeHttpRequest(url, method, null);
    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }
            is.close();
            json = sBuilder.toString();
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {

        }

        // return JSON String
        return jObj;

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public String makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            // check for request method
            if (method == "POST") {
                HttpPost httpPost = new HttpPost(url);
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            } else if (method == "GET") {
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);
                // DefaultHttpClient httpClient = new
                // DefaultHttpClient(httpParameters);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {

        }

        // return JSON String
        return json;

    }
}

為什么輸出只說:

{"data":[]}  

這是我的代碼:

package percobaan;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author nafian
 */
public class Coba {

    public static void main(String[] args) {
        ArrayList<HashMap<String, String>> daftar_d = new ArrayList<HashMap<String, String>>();
        JSONParser jsonParser = new JSONParser();
        String link_url = "http://api.pemiluapi.org/calonpresiden/api/caleg/jk?apiKey=56513c05217f73e6be82d5542368ae4f";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        String parsing = jsonParser.makeHttpRequest(link_url, "POST",
                params);

        System.out.print(parsing);
//        try {
//            JSONObject json = new JSONObject(parsing).getJSONObject("data").getJSONObject("results");
//            JSONArray caleg = json.getJSONArray("caleg");
//
//            for (int i = 0; i < caleg.length(); i++) {
//                HashMap<String, String> map = new HashMap<String, String>();
//                JSONObject ar = caleg.getJSONObject(i);
//                String nama = ar.getString("nama");
//                String calon = ar.getString("role");
//
//                JSONArray riwayat = ar.getJSONArray("riwayat_pendidikan");
//                for (int j = 0; j < riwayat.length(); j++) {
//                    JSONObject ringkasan = riwayat.getJSONObject(j);
//                    String ringkasan_p = ringkasan.getString("ringkasan");
//                    map.put("pendidikan_r", ringkasan_p);
//                }
//
//                map.put("nama", nama);
//                map.put("calon", calon);
//                daftar_d.add(map);
//
//            }
//        } catch (JSONException ex) {
//            ex.printStackTrace();
//        }
//        for (int i = 0; i < daftar_d.size(); i++) {
//
//            System.out.println(daftar_d.get(i).get("pendidikan_r").toString());
//        }

    }
}

我想念什么嗎?

我建議您使用JSON-SIMPLE,它將從字面上簡化您的生活。 https://code.google.com/p/json-simple/

這是給定URL的一個小示例。 請注意,這是我正在使用Jersey建立連接,但是您幾乎可以使用任何您喜歡的東西。

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;

...

String callString = "http://api.pemiluapi.org/calonpresiden/api/caleg/jk?apiKey=56513c05217f73e6be82d5542368ae4f";

Client client = Client.create();
WebResource webResource = client.resource(callString);

ClientResponse clientResponse = webResource.accept("application/json").get(ClientResponse.class);
if (clientResponse.getStatus() != 200) {
    throw new RuntimeException("Failed"+ clientResponse.toString());
}

JSONObject resObj = (JSONObject)new JSONParser().parse(clientResponse.getEntity(String.class));
JSONObject data_obj = (JSONObject) resObj.get("data");
JSONObject results_obj = (JSONObject) data_obj.get("results");
JSONArray caleg_array = (JSONArray) results_obj.get("caleg");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM