使用jackson解析json数据

import java.util.Iterator;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

public class Test {

	public static void main(String[] args) throws Exception {
		String str = "[{\"data\":{\"id\":\"1\",\"username\":\"username_1\",\"name\":\"name_1\"}},{\"data\":{\"id\":\"2\",\"username\":\"username_2\",\"name\":\"name_2\"}},{\"data\":{\"id\":\"3\",\"username\":\"username_3\",\"name\":\"name_3\"}},{\"data\":{\"id\":\"4\",\"username\":\"username_4\",\"name\":\"name_4\"}},{\"data\":{\"id\":\"5\",\"username\":\"username_5\",\"name\":\"name_5\"}},{\"data\":{\"id\":\"6\",\"username\":\"username_6\",\"name\":\"name_6\"}},{\"data\":{\"id\":\"7\",\"username\":\"username_7\",\"name\":\"name_7\"}},{\"data\":{\"id\":\"8\",\"username\":\"username_8\",\"name\":\"name_8\"}},{\"data\":{\"id\":\"9\",\"username\":\"username_9\",\"name\":\"name_9\"}},{\"data\":{\"id\":\"10\",\"username\":\"username_10\",\"name\":\"name_10\"}}]";
		ObjectMapper mapper = new ObjectMapper();
		JsonNode jsonNode = mapper.readValue(str, JsonNode.class);
		Iterator<JsonNode> nodes = jsonNode.getElements();
		while (nodes.hasNext()) {
			JsonNode node = nodes.next().get("data");
			System.out.print("id:"+node.get("id").getTextValue());
			System.out.print(" ");
			System.out.print("username:"+node.get("username").getTextValue());
			System.out.print(" ");
			System.out.println("name:"+node.get("name").getTextValue());
		}
	}
}

结果如下:
id:1 username:username_1 name:name_1
id:2 username:username_2 name:name_2
id:3 username:username_3 name:name_3
id:4 username:username_4 name:name_4
id:5 username:username_5 name:name_5
id:6 username:username_6 name:name_6
id:7 username:username_7 name:name_7
id:8 username:username_8 name:name_8
id:9 username:username_9 name:name_9
id:10 username:username_10 name:name_10

你可能感兴趣的:(json)