Java JsonParserDelegate-class And Method Code Example


Here is an example of how to use the JsonParserDelegate class from the org.apache.commons.io package in Java:

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.apache.commons.io.input.JsonParserDelegate;
import java.io.StringReader;

public class Main {
    public static void main(String[] args) throws Exception {
        String json = "{\"name\":\"John\",\"age\":30}";

        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jsonParser = jsonFactory.createJsonParser(new StringReader(json));
        JsonParserDelegate delegate = new JsonParserDelegate(jsonParser);

        while (delegate.nextToken() != JsonToken.END_OBJECT) {
            String fieldname = delegate.getCurrentName();
            if ("name".equals(fieldname)) {
                delegate.nextToken();
                System.out.println(delegate.getText());
            }
            if ("age".equals(fieldname)) {
                delegate.nextToken();
                System.out.println(delegate.getIntValue());
            }
        }
        delegate.close();
    }
}

In this example, we create a JsonFactory, JsonParser and JsonParserDelegate objects. We use the JsonParserDelegate object to parse a JSON string, and retrieve the values of the "name" and "age" fields. Finally, we close the JsonParserDelegate.

Please note that this class has been removed from apache.commons.io library, it was present in version 2.6, But as of latest version it has been removed, you can use other libraries like Jackson library's JsonParser to achieve similar functionality.