Use Jackson To Stream Parse an Array of Json Objects

前端 未结 4 1624
无人共我
无人共我 2020-12-05 11:19

I have a file that contains a json array of objects:

[ { \"test1\": \"abc\" }, { \"test2\": [1, 2, 3] } ]

I wish to use use

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 11:56

    What you are looking for is called Jackson Streaming API. Here is a code snippet using Jackson Streaming API that could help you to achieve what you need.

    JsonFactory factory = new JsonFactory();
    JsonParser parser = factory.createJsonParser(new File(yourPathToFile));
    
    JsonToken token = parser.nextToken();
    if (token == null) {
        // return or throw exception
    }
    
    // the first token is supposed to be the start of array '['
    if (!JsonToken.START_ARRAY.equals(token)) {
        // return or throw exception
    }
    
    // iterate through the content of the array
    while (true) {
    
        token = parser.nextToken();
        if (!JsonToken.START_OBJECT.equals(token)) {
            break;
        }
        if (token == null) {
            break;
        }
    
        // parse your objects by means of parser.getXxxValue() and/or other parser's methods
    
    }
    

提交回复
热议问题