如何使用jackson android解析json

时间:2014-03-06 09:44:51

标签: android json jackson

我正在制作一个webservice应用程序我正在获取json响应并且我正在解析json并且我在listview.Right中显示结果现在我想用jackson库解析。我尝试了一些但我没有得到任何东西。

代码:

private static class Holder
    {
        ArrayList<UpcomingPojo> holderlist;
    }


 ObjectMapper objmapper=new ObjectMapper();
                Holder holderPojo =objmapper.readValue(jsonResponse,Holder.class);

                     UpcomingPojo contact = holderPojo.holderlist.get(0);
                     String  name=contact.getName();

POJO:

@JsonIgnoreProperties(ignoreUnknown=true)
public class UpcomingPojo {

    String no,name,desc;

    public String getNo() {
        return no;
    }

    public String getName() {
        return name;
    }


}

JSON:

 [

   {
      "no":"12000",
      "name":"ram"

   },
   {
      "no":"12532",
      "name":"ravi"
   }
]

1 个答案:

答案 0 :(得分:0)

这是使用jackson库解析JSON的代码。

           try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            try {
                HttpResponse response = httpClient
                        .execute(new HttpGet(url));
                InputStream is = response.getEntity().getContent();

                JsonFactory factory = new JsonFactory();
                JsonParser jsonParser = factory.createJsonParser(is);
                JsonToken token = jsonParser.nextToken();

                if (token == JsonToken.START_ARRAY) {
                    while (token != JsonToken.END_ARRAY) {

                        token = jsonParser.nextToken();
                        if (token == JsonToken.START_OBJECT) {
                            while (token != JsonToken.END_OBJECT) {

                                token = jsonParser.nextToken();
                                if (token == JsonToken.FIELD_NAME) {
                                    String objectName = jsonParser
                                            .getCurrentName();
                                    jsonParser.nextToken();
                                    if (0 == objectName
                                            .compareToIgnoreCase("no")) {
                                        Log.d("","no="+jsonParser.getText());
                                    } else if (0 == objectName
                                            .compareToIgnoreCase("name")) {
                                        Log.d("","name="+jsonParser.getText());
                                    }


                                }


                            }

                        }




                    }
                }

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

            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d("", "exception2");

        }