javax.json.JsonObject接口可以表示一个不可变的JSON对象值,并提供到JSON对象名称/值映射的不可修改的映射视图。 可以使用javax.json.JsonReader类的静态方法readObject()从输入源创建JsonObject实例,也可以使用javax.json.Json类的静态方法createObjectBuilder()来创建JsonObject实例。
public static JsonObjectBuilder createObjectBuilder()
import java.io.*; import javax.json.*; public class JsonObjectTest { public static void main(String[] args) throws Exception { JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add("Name", "Adithya"); builder.add("Designation", "Python Developer"); builder.add("Company", "Nhooo"); builder.add("Location", "Hyderabad"); JsonObject data = builder.build(); StringWriter sw = new StringWriter(); JsonWriter jw = Json.createWriter(sw); jw.writeObject(data); jw.close(); System.out.println(sw.toString()); } }
输出结果
{"Name":"Adithya","Designation":"Python Developer","Company":"Nhooo","Location":"Hyderabad"}