簡體   English   中英

來自 API 的信息 - JSON

[英]Information from API - JSON

我嘗試從此鏈接獲取信息

我不明白!

這是我的代碼:

    String s = getJSONFile();
    String myDataArray[] = {};

    try{
        JSONObject reportJSON = new JSONObject();
        JSONArray dateJSON = reportJSON.getJSONArray("terrestrial_date");

        myDataArray = new String[dateJSON.length()];
        for (int i = 0; i <dateJSON.length(); i++){
            JSONObject jsonObject = dateJSON.getJSONObject(i);
            myDataArray[i] = jsonObject.getString("terrestrial_date");
        }
}catch (JSONException e){
        e.printStackTrace();
    }

    ArrayAdapter<String> stringAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.row, myDataArray);
    if (mListView != null){
        mListView.setAdapter(stringAdapter);
    }
}

這是 getJSONFile 方法:

public String getJSONFile() {
    String json = null;
    try {
        InputStream is = getResources().openRawResource(R.raw.weather_json);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

感謝幫助 :)

您應該使用 GSON 庫和此代碼的模型http://www.jsonschema2pojo.org/

這太容易了。

terrstial_date是報告的String 嘗試這個,

String date=jsonObject.getString("terestial_date");

也是你json解析structere是不正確的accroding您的json

{
"report": {
    "terrestrial_date": "2017-10-13",
    "sol": 1844,
    "ls": 73.0,
    "min_temp": -81.0,
    "min_temp_fahrenheit": -113.8,
    "max_temp": -28.0,
    "max_temp_fahrenheit": -18.4,
    "pressure": 869.0,
    "pressure_string": "Higher",
    "abs_humidity": null,
    "wind_speed": null,
    "wind_direction": "--",
    "atmo_opacity": "Sunny",
    "season": "Month 3",
    "sunrise": "2017-10-13T10:59:00Z",
    "sunset": "2017-10-13T22:43:00Z"
  }
}

你做錯了

1. report是您的responseJsonObject意味着您的report位於另一個JsonObject 首先,您必須解析您的響應以獲取report數據

2. terrestrial_date是一個string數據,所以你必須使用report.getJsonString("terrestrial_date")你正在使用reportJSON.getJSONArray("terrestrial_date"); 用於Array數據

有關更多信息,請查看此處如何在 Android 中解析 JSON

嘗試這個,

String s = getJSONFile();
String terrestrial_date = "";

     try{
        JSONObject responce = new JSONObject(s);
        JSONObject report= responce.getJSONObject("report");
        terrestrial_date = report.getString("terrestrial_date");

        }catch (JSONException e){
        e.printStackTrace();
    }

編輯

嘗試使用Volley獲取JSON數據

首先你需要在build.gradle文件中添加 volley 的依賴:

dependencies {
compile 'com.android.volley:volley:1.0.0'
}

然后使用以下代碼來獲取或解析您的JSON數據

// Tag used to cancel the request

String url = "http://marsweather.ingenology.com/v1/latest/?format=json";


StringRequest strReq = new StringRequest(Request.Method.GET,
                url, new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, response.toString());
                        String terrestrial_date = "";

                       try{
                          JSONObject responce = new JSONObject(response);
                          JSONObject report= responce.getJSONObject("report");
                          terrestrial_date = report.getString("terrestrial_date");

                       }catch (JSONException e){
                           e.printStackTrace();
                       }


                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, "Error: " + error.getMessage());

                    }
                });


    // Adding request to request queue
Volley.newRequestQueue(this).add(strReq);

截屏

在此處輸入圖片說明

作為,您可以看到上面的屏幕截圖。 我收到相同代碼的回復

這是您如何從OkHttp獲得響應

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("http://marsweather.ingenology.com/v1/latest/?format=json")
  .get()
  .build();

try {
        Response response = client.newCall(request).execute();
        String json = response.body().string();
        JSONObject jsonObject = new JSONObject(json);
        JSONObject reportJson =  jsonObject.getJSONObject("report"); // your report object.
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();

    }

將您的 Json 文件放在您的資產文件夾中,擴展名為 .json 並使用此方法從中獲取 JsonString

public String loadJSONFromAsset(String fileName) {
        String json = null;
        try {

            InputStream is = getAssets().open(fileName);

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

並像這樣使用此函數獲取字符串

String jsonString = MyApplication.loadJSONFromAsset(this,"yourJsonFileName.json");

並像這樣解析

try{
        JSONObject responce = new JSONObject(jsonString);
        JSONArray report= responce.getJSONObject("report");
        String terrestrial_date = report.getString("terrestrial_date");

}catch (JSONException e){
        e.printStackTrace();
    }

這是我所有更改后的代碼:

  public void find_weather() {
    String url = "http://marsweather.ingenology.com/v1/latest/?format=json";

    JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONObject main_object = response.getJSONObject("results");
                JSONArray array = response.getJSONArray("");
                JSONObject object = array.getJSONObject(0);
                String date = object.getString("date");
                String tempMin = String.valueOf(main_object.getDouble("min_temp"));
                String tempMax = String.valueOf(main_object.getDouble("max_temp"));
                String atmo_opacity = object.getString("atmo_opacity");

                mMaxTemp.setText("max_temp");
                mMinTemp.setText("min_temp");
                mAtmoOpacity.setText("atmo_opacity");

                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("EEEE-MM-dd");
                String formatted_data = sdf.format(calendar.getTime());
                mDate.setText(formatted_data);

                double temp_max_int = Double.parseDouble(tempMax);
                double temp_min_int = Double.parseDouble(tempMin);

                mMaxTemp.setText(String.valueOf(i));
                mMinTemp.setText(String.valueOf(i));


            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    RequestQueue queue = Volley.newRequestQueue(this);
    queue.add(jor);

暫無
暫無

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

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