您可以提供所有感兴趣的类都应该实现的接口。该接口应提供将当前对象转换为 JSON 的方法。参见示例:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class JsonProgram {
public static void main(String[] args) {
Root root = new Root(Arrays.asList(new Child(Arrays.asList(
new AnotherChild(1), new AnotherChild(2)))));
System.out.println(root.toJSON());
}
}
interface JsonState {
String toJSON();
}
class Root implements JsonState {
private List<Child> childs = new ArrayList<Child>();
public Root(List<Child> childs) {
this.childs = childs;
}
@Override
public String toJSON() {
StringBuilder builder = new StringBuilder();
builder.append("{").append("\"childs\"").append(":[");
int index = 0;
for (Child child : childs) {
builder.append(child.toJSON());
if (index < childs.size() - 1) {
builder.append(",");
}
index++;
}
builder.append("]\"}");
return builder.toString();
}
}
class Child implements JsonState {
private List<AnotherChild> anotherChilds = new ArrayList<AnotherChild>();
public Child(List<AnotherChild> anotherChilds) {
this.anotherChilds = anotherChilds;
}
@Override
public String toJSON() {
StringBuilder builder = new StringBuilder();
builder.append("{").append("\"anotherChilds\"").append(":[");
int index = 0;
for (AnotherChild child : anotherChilds) {
builder.append(child.toJSON());
if (index < anotherChilds.size() - 1) {
builder.append(",");
}
index++;
}
builder.append("]}");
return builder.toString();
}
}
class AnotherChild implements JsonState {
private int value;
public AnotherChild(int value) {
this.value = value;
}
@Override
public String toJSON() {
StringBuilder builder = new StringBuilder();
builder.append("{").append("\"value\"").append(":\"").append(value)
.append("\"}");
return builder.toString();
}
}
输出:
{
"childs":[
{
"anotherChilds":[
{
"value":"1"
},
{
"value":"2"
}
]
}
]
}
但这不是一个好的解决方案。而不是实现您自己的解决方案,您应该使用一些可以为您完成的库。我向您推荐google-gson。对我来说是最好的。
编辑 - GSON 示例
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonProgram {
public static void main(String[] args) {
Root root = new Root(Arrays.asList(new Child(Arrays.asList(
new AnotherChild(1), new AnotherChild(2)))));
Gson gson = new GsonBuilder().serializeNulls().create();
System.out.println(gson.toJson(root));
}
}
class Root {
private List<Child> childs = new ArrayList<Child>();
public Root(List<Child> childs) {
this.childs = childs;
}
@Override
public String toString() {
return Arrays.toString(childs.toArray());
}
}
class Child {
private List<AnotherChild> anotherChilds = new ArrayList<AnotherChild>();
public Child(List<AnotherChild> anotherChilds) {
this.anotherChilds = anotherChilds;
}
@Override
public String toString() {
return Arrays.toString(anotherChilds.toArray());
}
}
class AnotherChild {
private int value;
public AnotherChild(int value) {
this.value = value;
}
@Override
public String toString() {
return Integer.toString(value);
}
}
上面的示例创建相同的输出。对我来说,这是一个更优雅的解决方案。