0

我很难弄清楚如何从这个 JSON 中获取数据:

{
data: {
       current_condition: [
             {
              cloudcover: "100",
              humidity: "74",
              observation_time: "06:53 PM",
              precipMM: "4.5",
              pressure: "1009",
              temp_C: "26",
              temp_F: "79",
              visibility: "16",
              weatherCode: "356",
              weatherDesc: [
                 {
                   value: "Moderate or heavy rain shower"
                 }
                ] ,
              weatherIconUrl: [
                 {
                   value: "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0010_heavy_rain_showers.png"
                 }
                ],
              winddir16Point: "N",
              winddirDegree: "10",
              windspeedKmph: "11",
              windspeedMiles: "7"
      }
     ],
       nearest_area: [
           {
              areaName: [
                 {
                   value: "New York"
                 }
              ],
              country: [
                 {
                   value: "United States Of America"
                 }
              ],
              latitude: "40.714",
              longitude: "-74.006",
              population: "8107916",
              region: [
                 {
                   value: "New York"
                 }
              ],
              weatherUrl: [
                 {
                   value: "http://free.worldweatheronline.com/New-York-weather/New-York/US.aspx"
                 }
              ]
       }
     ],
       request: [
          {
            query: "New York, United States Of America",
            type: "City"
          }
         ]
        }
       }

我正在使用 GSON 来解析它,所以我应该有一个非空对象作为结果。我目前的课程是:

气象信息:

  public class MeteoInfo {

public MeteoInfo(){}
@SerializedName("current_condition")
private List<CurrentCondition> currentCondition;

@SerializedName("nearest_area")
private List<NearestArea> nearestArea;

public List<CurrentCondition> getCurrentCondition(){
    return currentCondition;
}
public List<NearestArea> getNearestArea(){
    return nearestArea;
}
    }

现在的状况:

  public class CurrentCondition{

@SerializedName("weatherCode")
private int weatherCode;
@SerializedName("weatherDesc")
private List<Value> weatherDescs;
@SerializedName("temp_C")
private String temp_C;
@SerializedName("observation_time")
private String observation_time;


public int getWeatherCode() {
    return weatherCode;
}

public void setWeatherCode(int weatherCode) {
    this.weatherCode = weatherCode;
}

public List<Value> getweatherDescs() {
    return weatherDescs;
}

public void setweatherDescs(List<Value> weatherText) {
    this.weatherDescs = weatherText;
}

public String weatherDescsToString(){
    String description= "";

    if (weatherDescs!=null){
        for (Value values:weatherDescs){
            description= description + values.getValue();
        }}
    return description;
}

public String getTemp_C() {
    return temp_C;
}

public void setTemp_C(String temp_C) {
    this.temp_C = temp_C;
}



public String getObservation_time() {
    return observation_time;
}

public void setObservation_time(String observation_time) {
    this.observation_time = observation_time;
}
public class Value{
    @SerializedName("value")
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

}

和最近区域:

   public class NearestArea{
@SerializedName("areaName")
private List<Value> areaNames;
@SerializedName("country")
private List<Value> countries;
@SerializedName("latitude")
private String latitude;
@SerializedName("longitude")
private String longitude;
@SerializedName("region")
private List<Value> regions;
@SerializedName("weatherUrl")
private List<Value> urls;


public List<Value> getAreaNames() {
    return areaNames;
}
public void setAreaNames(List<Value> areaNames) {
    this.areaNames = areaNames;
}
public List<Value> getCountries() {
    return countries;
}
public void setCountries(List<Value> countries) {
    this.countries = countries;
}
public String getLatitude() {
    return latitude;
}
public void setLatitude(String latitude) {
    this.latitude = latitude;
}
public String getLongitude() {
    return longitude;
}
public void setLongitude(String longitude) {
    this.longitude = longitude;
}
public List<Value> getRegions() {
    return regions;
}
public void setRegions(List<Value> regions) {
    this.regions = regions;
}
public List<Value> getUrls() {
    return urls;
}
public void setUrls(List<Value> urls) {
    this.urls = urls;
}

public class Value{
    @SerializedName("value")
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

}

我认为它应该像现在一样好(但改进建议被很好地接受),但我不知道如何在较低级别获取字符串,如weatherDesc的字符串或areaNames的字符串。编辑:我的课程中是否需要所有来自 json 的变量,或者我可以跳过那些我不需要的变量?

EDIT2:我修改了 MeteoInfo 类。这是获取 json 并对其进行解析的代码:

    private class MeteoRetrieverAsyncTask extends AsyncTask<Void, Void, Void> {



    private int weatherCode;
    private String tempC;
    private String observationTime;
    private String weatherDesc;
    private String latitude;
    private String longitude;
    private String areaName;
    private String country;
    private String region;
    private String url;
    private MeteoInfo meteoInfo;

    @Override
    protected Void doInBackground(Void... params) {
        MeteoJsonParser msp = new MeteoJsonParser();
        String url=apiBuilder();
        try {
            data= msp.getJSONData(url);
        } catch (Exception e) {
            e.printStackTrace();
        } 
        if (data!=null){
            try {
                meteoInfo= msp.parseJson(data);

            } catch (FileNotFoundException e) {

                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        //Prendo i valori di CurrentCondition
        for (CurrentCondition ccondition : meteoInfo.getCurrentCondition()) {
            weatherCode= ccondition.getWeatherCode();

            tempC= ccondition.getTemp_C();
            observationTime = ccondition.getObservation_time();
            for (CondValue wDesc: ccondition.getweatherDescs()){
                weatherDesc= wDesc.getValue();
            }
            //Prendo i valori di NearestArea
            for (NearestArea nArea: meteoInfo.getNearestArea()){
                latitude = nArea.getLatitude();
                longitude = nArea.getLongitude();

                for (AreaValue aName: nArea.getAreaNames()){
                    areaName= aName.getValue();
                }
                for (AreaValue aCountry: nArea.getCountries()){
                    country = aCountry.getValue();
                }
                for (AreaValue aRegion: nArea.getRegions()){
                    region= aRegion.getValue();
                }
                for (AreaValue aUrl: nArea.getUrls()){
                    url= aUrl.getValue();
                }

            }

            //Scrivo i valori sullo schermo
            tv4.setText(tempC);
            tv1.setText(weatherCode);
            tv2.setText(weatherDesc);
            tv3.setText(observationTime);
            tv5.setText(latitude);
            tv6.setText(longitude);
            tv7.setText(areaName);
        }


        progressDialog.cancel();
    }

}

private class CancelListener implements OnCancelListener {

    AsyncTask<?, ?, ?> cancellableTask;

    public CancelListener(AsyncTask<?, ?, ?> task) {
        cancellableTask = task;
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        cancellableTask.cancel(true);
    }

}

MeteoJSONParser(在前面的代码中调用):

    public class MeteoJsonParser {


public MeteoJsonParser() {
    }

public  InputStream getJSONData(String url) throws Exception {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters,3000);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    URI uri;
    InputStream data = null;
    try {
        uri = new URI(url);
        HttpGet method = new HttpGet(uri);
        HttpResponse response = httpClient.execute(method);
        data = response.getEntity().getContent();
    } catch (Exception e) {
        Log.e("TAG","Unable to download file: "+e);
        throw e;
    }
    return data;
}
public MeteoInfo parseJson(InputStream inputStream) throws FileNotFoundException{
Gson gson = new Gson();
Reader r = new InputStreamReader(inputStream);
MeteoInfo dati = new MeteoInfo();
try {
        dati = gson.fromJson(r, MeteoInfo.class);

} catch (Exception e) {
        Log.e("JSON_Parser",e.toString());
}finally{
    Log.d("JSON OK", "JSON Parsed");
}
return dati;
}
}

我在这一行得到一个 NullPointerException :

   for (CurrentCondition ccondition : meteoInfo.getCurrentCondition()) 
4

1 回答 1

0
{
"contacts": [
    {
            "id": "c200",
            "name": "xyz",
            "email": "xyz@gmail.com",
            "address": "abcdertuuu",
            "gender" : "male",
            "phone": {
                         "mobile": "+91 0000000000",
                          "home": "00 000000",
                           "office": "00 000000"
                     }
    },





     try {
         // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);

      // looping through All Contacts
     for(int i = 0; i < contacts.length(); i++){
           JSONObject c = contacts.getJSONObject(i);

        // Storing each json item in variable
    String id = c.getString(TAG_ID);
    String name = c.getString(TAG_NAME);
    String email = c.getString(TAG_EMAIL);
    String address = c.getString(TAG_ADDRESS);
    String gender = c.getString(TAG_GENDER);

       // Phone number is agin JSON Object
    JSONObject phone = c.getJSONObject(TAG_PHONE);
    String mobile = phone.getString(TAG_PHONE_MOBILE);
    String home = phone.getString(TAG_PHONE_HOME);
    String office = phone.getString(TAG_PHONE_OFFICE

根据您的情况,最好创建一个递归函数

于 2012-09-06T11:51:28.080 回答