JsonParserDemo.java
1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
*
*/
package com.waylau.netty.demo.codec.jackcon;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
/**
* 说明:
*
* @author <a href="http://www.waylau.com">waylau.com</a> 2015年11月8日
*/
public class JsonParserDemo {
private static final String FILE_PATH = "d:\\user.json";
/**
*
*/
public JsonParserDemo() {
// TODO Auto-generated constructor stub
}
/**
* @param args
* @throws IOException
* @throws JsonParseException
*/
public static void main(String[] args) throws JsonParseException,
IOException {
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createJsonParser(new File(FILE_PATH));
// loop until token equal to "}"
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("name".equals(fieldname)) {
// current token is "name",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getText()); // display mkyong
}
if ("age".equals(fieldname)) {
// current token is "age",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getIntValue()); // display 29
}
if ("messages".equals(fieldname)) {
jParser.nextToken(); // current token is "[", move next
// messages is array, loop until token equal to "]"
while (jParser.nextToken() != JsonToken.END_ARRAY) {
// display msg1, msg2, msg3
System.out.println(jParser.getText());
}
}
}
jParser.close();
}
}