javax.json.JsonArray接口可代表不可变JSON数组,并提供一个不可修改的列表的数组中的值的图。甲JsonArray目的可以通过从输入源读取JSON数据,并且还使用静态方法创建createArrayBuilder()的javax.json.Json类。为了执行它,我们需要导入javax.json包(下载javax.json-api.jar文件)。
语法public static JsonArrayBuilder createArrayBuilder()
示例import java.io.*;
import javax.json.*;
import javax.json.JsonObjectBuilder;
public class JsonArrayTest {
public static void main(String[] args) {
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("Name", "Raja Ramesh");
builder.add("Designation", "Java Developer");
builder.add("Company", "nhooo");
JsonArray contactInfo = Json.createArrayBuilder().add(Json.createObjectBuilder().add("email", "raja@gmail.com")).add(Json.createObjectBuilder().add("mobile", "9959984000")).build();
builder.add("contactInfo", contactInfo);
JsonObject data = builder.build();
StringWriter sw = new StringWriter();
JsonWriter jw = Json.createWriter(sw);
jw.writeObject(data);
jw.close();
System.out.println(sw.toString());
}
}
输出结果{"Name":"Raja Ramesh","Designation":"Java Developer","Company":"nhooo",
"contactInfo":[{"email":"raja@gmail.com"},{"mobile":"9959984000"}]}