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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21825184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:08:42  来源:igfitidea点击:

How to parse json response using Hymanson in android?

androidjsonHymanson

提问by skyshine

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

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

json:

json:

{
    "contacts": [
        {
                "id": "c200",
                "name": "ravi raja",
                "email": "[email protected]",
                "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": "[email protected]",
                "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);

采纳答案by vilpe89

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 Hymanson parse it.

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

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) annotationmakes sure that you are not getting exceptions when your class doesnt contain property which is in the json, like addressin your json could give an exception, OR homein Phone object.

@JsonIgnoreProperties(ignoreUnknown=true) 注释可确保当您的类不包含 json 中的属性时,您不会收到异常,例如address在您的 json 中可能会给出异常,或者home在 Phone 对象中。

回答by Indrajit Sinh Rayjada

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 类!很酷 !

回答by Raj Kumar

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 中存储一个 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();
 }