How to parse json response using Jackson in android?

前端 未结 3 1677
醉梦人生
醉梦人生 2021-01-02 08:51

I am getting some json response by hitting url. I want to use jackson to parse json response. I tried with object Mapper but I am getting exceptions.

json:



        
3条回答
  •  长发绾君心
    2021-01-02 09:16

    As I can see your json is not array but is object that holds one object containing an array so you need to create a temporary dataholder class where to make the Jackson parse it.

    private static class ContactJsonDataHolder {
        @JsonProperty("contacts")
        public List mContactList;
    }
    
    public List getContactsFromJson(String json) throws JSONException, IOException {
    
        ContactJsonDataHolder dataHolder = new ObjectMapper()
            .readValue(json, ContactJsonDataHolder.class);
    
        // ContactPojo contact = dataHolder.mContactList.get(0);
        // String name = contact.getName();
        // String phoneNro = contact.getPhone().getMobileNro();
        return dataHolder.mContactList;
    }
    

    And little tweaks for your class:

    @JsonIgnoreProperties(ignoreUnknown=true)
    public class ContactPojo {
    
        String name, email, gender;
        Phone phone;
    
        @JsonIgnoreProperties(ignoreUnknown=true)
        public static class Phone {
    
             String mobile;
    
             public String getMobileNro() {
                  return mobile;
             }
        }
    
        // ...
    
        public Phone getPhone() {
            return phone;
        }
    

    @JsonIgnoreProperties(ignoreUnknown=true) annotation makes sure that you are not getting exceptions when your class doesnt contain property which is in the json, like address in your json could give an exception, OR home in Phone object.

提交回复
热议问题