【问题标题】:Jackson parsing in Android杰克逊在Android中解析
【发布时间】:2015-03-26 10:32:02
【问题描述】:

所以我一直在努力用 Jackson 解析 JSON。我尝试了很多例子,但没有一个有效。你能告诉我我哪里错了吗?

我正在使用Jackson 1.9.11 库。

型号:

@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();
        }

    }
}

}

所以现在我可以从WeatherInfo 类中检索name,但是当我尝试获取Wind speedMain tempMain humidity 时,我得到空指针异常,可能是因为Json 没有绑定到这些变量。有任何想法吗?提前致谢

【问题讨论】:

  • 先发布你的结果字符串
  • @user1992200 帖子已编辑

标签: android json jackson


【解决方案1】:

除非您使用@JsonCreator 注解,否则Json 无法与默认构造函数以外的自定义构造函数一起正常工作。

试试这个模型:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2019-07-27
    • 2014-08-22
    • 2019-11-25
    • 2012-09-11
    相关资源
    最近更新 更多