例
在 C:\>Jackson_WORKSPACE 中创建一个名为“JacksonTester”的 Java 类文件。
文件: JacksonTester.java
import java.io.IOException;
import java.util.Iterator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
try {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
JsonNode rootNode = mapper.readTree(jsonString);
JsonNode nameNode = rootNode.path("name");
System.out.println("Name: "+ nameNode.textValue());
JsonNode ageNode = rootNode.path("age");
System.out.println("Age: " + ageNode.intValue());
JsonNode verifiedNode = rootNode.path("verified");
System.out.println("Verified: " + (verifiedNode.booleanValue() ? "Yes":"No"));
JsonNode marksNode = rootNode.path("marks");
Iterator<JsonNode> iterator = marksNode.elements();
System.out.print("Marks: [ ");
while (iterator.hasNext()) {
JsonNode marks = iterator.next();
System.out.print(marks.intValue() + " ");
}
System.out.println("]");
}
catch (JsonParseException e) { e.printStackTrace(); }
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
}
验证结果
使用 javac 编译器编译类,如下所示:
C:\Jackson_WORKSPACE>javac JacksonTester.java
现在运行 JacksonTester 以查看结果:
C:\Jackson_WORKSPACE>java JacksonTester
验证输出
Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]