How to parse json response using Jackson in android?

前端 未结 3 1681
醉梦人生
醉梦人生 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:11

    Example Json data

    {
      "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

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

提交回复
热议问题