【问题标题】:How to parse json response using Jackson in android?如何在android中使用Jackson解析json响应?
【发布时间】:2014-02-17 09:26:28
【问题描述】:

我通过点击 url 得到一些 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:

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

}

代码:

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

【问题讨论】:

  • 发布您的解析代码。

标签: android json jackson


【解决方案1】:

我可以看到您的 json 不是数组,而是包含一个包含数组的对象的对象,因此您需要创建一个临时数据持有者类来让 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;
}

对您的班级进行一些小调整:

@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) 注释 确保当您的类不包含 json 中的属性时不会出现异常,例如 json 中的 address 可能会给出异常,或 home 在 Phone 对象中。

【讨论】:

  • 我有一个疑问 ==> contact.getPhone in String phoneNro = contact.getPhone.getMobileNro();
  • 是的,谢谢,写得这么快,所以我错过了来自 getPhone 的() :)
【解决方案2】:

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

您需要提供您的 json 数据,并根据该数据为您创建 pojo / Model 类!很酷!

【讨论】:

  • 不直接回答问题,但它是一个非常有用的工具,我从来没有见过!
【解决方案3】:

Json 数据示例

{
  "records": [

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

您需要在assert forder中存储一个sample.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();
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多