如何在android中使用Jackson解析json响应?

时间:2022-10-22 20:46:45

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.

我通过点击url得到一些json响应。我想使用jackson解析json响应。我尝试了对象映射器,但是我得到了异常。

json:

json:

{
    "contacts": [
        {
                "id": "c200",
                "name": "ravi raja",
                "email": "raja@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c201",
                "name": "Johnny Depp",
                "email": "johnny_depp@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },

    ]
}

pojo:

pojo:

public class ContactPojo {

    String name,email,gender,mobileno;

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getMobileno() {
        return mobileno;
    }

    public void setMobileno(String mobileno) {
        this.mobileno = mobileno;
    }

}

code:

代码:

ObjectMapper mapper=new ObjectMapper();
             userData=mapper.readValue(jsonResponse,ContactPojo.class);

3 个解决方案

#1


6  

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.

正如我看到的,json不是数组,而是包含一个包含数组的对象的对象,因此需要创建一个临时的dataholder类,以便Jackson解析它。

private static class ContactJsonDataHolder {
    @JsonProperty("contacts")
    public List<ContactPojo> mContactList;
}

public List<ContactPojo> 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.

@JsonIgnoreProperties(ignoreUnknown=true)注释确保在类不包含json中的属性时,不会出现异常,比如json中的地址可能会给出异常,或者在Phone对象中有home。

#2


3  

Well i always create my Model / Pojo class using jsonschema2pojo.org!

我总是使用jsonschema2pojo.org创建我的模型/ Pojo类!

you need to provide your json data and based on that data it will create pojo / Model class for you ! very cool !

您需要提供json数据,基于这些数据,它将为您创建pojo / Model类!非常酷!

#3


-1  

Example Json data

示例Json数据

{
  "records": [

    {"field1": "outer", "field2": "thought"},
    {"field2": "thought", "field1": "outer"}
  ] ,
  "special message": "hello, world!"
}

You need to store a sample.json in assert forder and then code is

您需要存储一个示例。在assert forder中的json,然后代码是

try
{

    InputStreamReader foodDataIn = new InputStreamReader(getAssets().open("sample.json"));
    ObjectMapper mapper = new ObjectMapper();
    JsonParser jp = mapper.getFactory().createParser(foodDataIn);
    JsonToken current;

    current = jp.nextToken();
    if (current != JsonToken.START_OBJECT) {
        System.out.println("Error: root should be object: quiting.");
        return;
    }
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldName = jp.getCurrentName();
        // move from field name to field value
        current = jp.nextToken();
        System.out.println("NAme: " +fieldName);
        if (fieldName.equals("records")) {
            if (current == JsonToken.START_ARRAY) {
                // For each of the records in the array
                 while (jp.nextToken() != JsonToken.END_ARRAY) {
                     // read the record into a tree model,
                     // this moves the parsing position to the end of it
                     JsonNode node = jp.readValueAsTree();
                     // And now we have random access to everything in the object
                     System.out.println("field1: " + node.get("field1").asText());
                     System.out.println("field2: " + node.get("field2").asText());
                 }
             } else {
                 System.out.println("Error: records should be an array: skipping.");
                 jp.skipChildren();
             }
         } else {
             System.out.println("Unprocessed property: " + fieldName);
             jp.skipChildren();
         }
     }      
 } catch (IOException e) {
     e.printStackTrace();
 }

#1


6  

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.

正如我看到的,json不是数组,而是包含一个包含数组的对象的对象,因此需要创建一个临时的dataholder类,以便Jackson解析它。

private static class ContactJsonDataHolder {
    @JsonProperty("contacts")
    public List<ContactPojo> mContactList;
}

public List<ContactPojo> 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.

@JsonIgnoreProperties(ignoreUnknown=true)注释确保在类不包含json中的属性时,不会出现异常,比如json中的地址可能会给出异常,或者在Phone对象中有home。

#2


3  

Well i always create my Model / Pojo class using jsonschema2pojo.org!

我总是使用jsonschema2pojo.org创建我的模型/ Pojo类!

you need to provide your json data and based on that data it will create pojo / Model class for you ! very cool !

您需要提供json数据,基于这些数据,它将为您创建pojo / Model类!非常酷!

#3


-1  

Example Json data

示例Json数据

{
  "records": [

    {"field1": "outer", "field2": "thought"},
    {"field2": "thought", "field1": "outer"}
  ] ,
  "special message": "hello, world!"
}

You need to store a sample.json in assert forder and then code is

您需要存储一个示例。在assert forder中的json,然后代码是

try
{

    InputStreamReader foodDataIn = new InputStreamReader(getAssets().open("sample.json"));
    ObjectMapper mapper = new ObjectMapper();
    JsonParser jp = mapper.getFactory().createParser(foodDataIn);
    JsonToken current;

    current = jp.nextToken();
    if (current != JsonToken.START_OBJECT) {
        System.out.println("Error: root should be object: quiting.");
        return;
    }
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldName = jp.getCurrentName();
        // move from field name to field value
        current = jp.nextToken();
        System.out.println("NAme: " +fieldName);
        if (fieldName.equals("records")) {
            if (current == JsonToken.START_ARRAY) {
                // For each of the records in the array
                 while (jp.nextToken() != JsonToken.END_ARRAY) {
                     // read the record into a tree model,
                     // this moves the parsing position to the end of it
                     JsonNode node = jp.readValueAsTree();
                     // And now we have random access to everything in the object
                     System.out.println("field1: " + node.get("field1").asText());
                     System.out.println("field2: " + node.get("field2").asText());
                 }
             } else {
                 System.out.println("Error: records should be an array: skipping.");
                 jp.skipChildren();
             }
         } else {
             System.out.println("Unprocessed property: " + fieldName);
             jp.skipChildren();
         }
     }      
 } catch (IOException e) {
     e.printStackTrace();
 }