您可以手动构建和打印 JSON,但您可能希望使用 SimpleJSON、Jackson 2 或 GSON,随着数据变得更加复杂,它们会更适合您:
SimpleJSON: https://github.com/fangyidong/json-simple , JAR
GSON:https : //github.com/google/gson,JAR
//Simple JSON
import org.json.simple.JSONObject;
//GSON
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JSONExamples {
public static void main(String[] args) {
String id = "123";
String title = "Very Important Record";
//Simple JSON
JSONObject obj = new JSONObject();
obj.put("id", id);
obj.put("title", title);
System.out.println(obj);
//GSON
MyRecord myImportantRecord = new MyRecord(id, title);
Gson gson = new GsonBuilder().create();
gson.toJson(myImportantRecord, System.out);
}
}
我的记录.java:
public class MyRecord {
private String id;
private String title;
MyRecord(String id, String title) {
this.id=id;
this.title=title;
}
}