{“Getting”:”started”}
翻译:(JSON-P) https://javaee.github.io/jsonp/getting-started.html
这是一篇JSON-P操作快速入门指导手册。
添加依赖
添加如下的依赖关系:
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1</version>
</dependency>
读/写 JSON
JSON-P主要的接入点是 Json 类,它提供了所有必要的方法(对JSON)进行分析处理,并且用java构建JSON字符串。Json 是一个为JSON-P API 所有元素提供静态工厂方法的单例。
// Create Json and print
JsonObject json = Json.createObjectBuilder()
.add("name", "Falco")
.add("age", BigDecimal.valueOf(3))
.add("biteable", Boolean.FALSE).build();
String result = json.toString();
System.out.println(result);
// Read back
JsonReader jsonReader = Json.createReader(new StringReader("{\"name\":\"Falco\",\"age\":3,\"bitable\":false}"));
JsonObject jobj = jsonReader.readObject();
System.out.println(jobj);
// Output
{"name":"Falco","age":3,"biteable":false}
{"name":"Falco","age":3,"bitable":false}
解析JSON
JSON-P 的API Stream提供了对于JSON 字符串的解析。不同于对象模型,JSON-P API为可能发生属性或者结构变化的字符串提供了更为通用的接口。Stream API 更有利于处理很大的JSON 字符串,特别是当使用对象模型API 在统一读取的时候将会占用很大内存。
// Parse back
final String result = "{\"name\":\"Falco\",\"age\":3,\"bitable\":false}";
final JsonParser parser = Json.createParser(new StringReader(result));
String key = null;
String value = null;
while (parser.hasNext()) {
final Event event = parser.next();
switch (event) {
case KEY_NAME:
key = parser.getString();
System.out.println(key);
break;
case VALUE_STRING:
String string = parser.getString();
System.out.println(string);
break;
case VALUE_NUMBER:
BigDecimal number = parser.getBigDecimal();
System.out.println(number);
break;
case VALUE_TRUE:
System.out.println(true);
break;
case VALUE_FALSE:
System.out.println(false);
break;
}
}
parser.close();
}
// Output
name
Falco
age
3
bitable
false
注:这是JSON 为JAVA提供的API,是一款非常好用的API。后面我将会继续对帮助文档进行翻译。