来自API的信息 - JSON

时间:2017-10-17 09:20:48

标签: android arrays json

我尝试从此link

获取信息

我不明白!

这是我的代码:

    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;
}

感谢您的帮助:)

6 个答案:

答案 0 :(得分:0)

您应该使用GSON图书馆和此代码的模型http://www.jsonschema2pojo.org/

这很容易。

答案 1 :(得分:0)

terrstial_dateString报告。试试这个,

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

您的json解析结果也不正确地归结为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"
  }
}

答案 2 :(得分:0)

你做错了

1. report JsonObjectresponse表示您将 report 置于另一个JsonObject内{1}}。首先,您必须解析您的回复才能获得 report 数据

2. terrestrial_date 是一个string数据,因此您必须使用report.getJsonString("terrestrial_date") reportJSON.getJSONArray("terrestrial_date");用于Array数据

有关更多信息,请点击此处 How to parse JSON in Android

试试这个,

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文件中添加排球依赖项 - :

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);

<强> SCREENSHOT

enter image description here

As,您可以看到上面的截图。我收到的回复是相同的代码

答案 3 :(得分:0)

这是您从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();

    }

答案 4 :(得分:0)

将您的Json文件放在您的assets文件夹中,扩展名为.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

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

和Parse一样

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

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

答案 5 :(得分:0)

在完成所有更改后,这是我的代码:

  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);