Iva Stojkovic
Iva Stojkovic

Reputation: 27

Jackson parsing in Android

So i have been struggling with parsing JSON with Jackson. I have tried many examples but none of them worked. Can you tell me where I am wrong?

I'm using Jackson 1.9.11 library.

Model:

@JsonIgnoreProperties(ignoreUnknown=true)
public class WeatherInfo {

    private String name; //City Name
    private Wind speed;
    private Main temp;
    private Main humidity;

    public WeatherInfo() {

    }

    public WeatherInfo(String name) {

        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Wind getSpeed() {
        return speed;
    }

    public void setSpeed(Wind speed) {
        this.speed = speed;
    }

    public Main getTemp() {
        return temp;
    }

    public void setTemp(Main temp) {
        this.temp = temp;
    }

    public Main getHumidity() {
        return humidity;
    }

    public void setHumidity(Main humidity) {
        this.humidity = humidity;
    }


@JsonIgnoreProperties(ignoreUnknown=true)
public class Main {

    public float temp;
    public int humidity;

    public Main(){}

    public Main(float temp, int humidity) {

        this.temp = temp;
        this.humidity = humidity;
    }

    public float getTemp() {
        return temp;
    }
    public void setTemp(float temp) {
        this.temp = temp;
    }
    public int getHumidity() {
        return humidity;
    }
    public void setHumidity(int humidity) {
        this.humidity = humidity;
    }   

}

@JsonIgnoreProperties(ignoreUnknown=true)
public class Wind {

    private float speed;

     public Wind(){}

     public Wind(float speed) {

        this.speed = speed;
     }

    public float getSpeed() {
        return speed;
    }

    public void setSpeed(float speed) {
        this.speed = speed;
    }   
}       


public class WeatherService extends Service {

private BroadcastReceiver receiver = new BroadcastReceiver(){
    public void onReceive(Context context, Intent intent){
        int position = intent.getIntExtra("position", 0);
        switch(position){   
        case 0 : new ReadTask().execute("http://api.openweathermap.org/data/2.5/weather?q=Belgrade&APPID=c7530dc8eed20058b9906a24801c7741"); break;
        case 1 : new ReadTask().execute("http://api.openweathermap.org/data/2.5/weather?q=London&APPID=c7530dc8eed20058b9906a24801c7741"); break;
        case 2 : new ReadTask().execute("http://api.openweathermap.org/data/2.5/weather?q=Paris&APPID=c7530dc8eed20058b9906a24801c7741"); break;
        }

    }
};

public IBinder onBind(Intent arg0){
    return null;
}

public int onStartCommand(Intent intent, int flags, int startId){

    IntentFilter filter = new IntentFilter();
    filter.addAction("PROBA");
    registerReceiver(receiver, filter);
    return START_STICKY;
}

public void onDestroy(){
    super.onDestroy();
}

public String readJSONString(String url){
    StringBuilder stringBuilder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try{

        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int code = statusLine.getStatusCode();
        if(code == 200){    
            HttpEntity entity = response.getEntity();   
            InputStream content = entity.getContent();  

            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while((line = reader.readLine()) != null)
                stringBuilder.append(line);
        }
        else{
            Log.e("JSON", "Fail");
        }
    }
    catch(ClientProtocolException e){
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }   

    return stringBuilder.toString();
}


private class ReadTask extends AsyncTask<String, Void, String> {


    protected String doInBackground(String... urls){

        return readJSONString(urls[0]);
    }


    protected void onPostExecute(String result){

        ObjectMapper mapper = new ObjectMapper();

        Log.e("PARSERJSON", "JSON is : "+  result);
        //Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();

        try {


            Weather w = mapper.readValue(result, Weather.class);

            //Toast.makeText(getBaseContext(), "name is" + w.getName(), Toast.LENGTH_LONG).show();


        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

}

So now i can retrieve name from WeatherInfo class, but when i try to get Wind speed or Main temp and Main humidity i get null pointer exception, probably because Json is not binded to these variables. Any ideas? Thanks in advance

Upvotes: 1

Views: 123

Answers (1)

murielK
murielK

Reputation: 1030

Json wont work well with custom constructor other than the default one unless you use @JsonCreator annotation.

try this model:

@JsonIgnoreProperties(ignoreUnknown=true)
public class Weather {

    private String name;

    @JsonCreator
    public Weather(@JsonProperty("name") String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Upvotes: 1

Related Questions