我们以 Gson 为例:
您可以使用 Gson 自定义序列化器,如下所示(我创建类 Users,否则其他 List 将使用 MySerializer,这不是预期的)
import com.google.common.collect.Lists;
import com.google.gson.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static class User {
private List<Integer> ids;
private List<String> names;
public User(List<Integer> ids, List<String> names) {
this.ids = ids;
this.names = names;
}
}
public static class Users extends ArrayList<User> {
}
public static void main(String[] args) {
Users users = new Users();
users.add(new User(Lists.newArrayList(1, 2, 3), Lists.newArrayList("anton", "berta", "charlie")));
users.add(new User(Lists.newArrayList(4, 5, 6), Lists.newArrayList("dora", "emil", "friedrich")));
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Users.class, new MySerializer());
System.out.printf(gsonBuilder.create().toJson(users));
}
public static class MySerializer implements JsonSerializer<Users> {
@Override
public JsonElement serialize(Users users, Type type, JsonSerializationContext jsonSerializationContext) {
JsonObject jsonObject = new JsonObject();
for (int i = 0; i < users.size(); i++) {
jsonObject.add(String.valueOf(i + 1), jsonSerializationContext.serialize(users.get(i)));
}
return jsonObject;
}
}
}
另一种简单的方法是将list放入map然后制作json,比如
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static class User {
private List<Integer> ids;
private List<String> names;
public User(List<Integer> ids, List<String> names) {
this.ids = ids;
this.names = names;
}
}
public static void main(String[] args) {
List<User> users = new ArrayList<User>();
users.add(new User(Lists.newArrayList(1, 2, 3), Lists.newArrayList("anton", "berta", "charlie")));
users.add(new User(Lists.newArrayList(4, 5, 6), Lists.newArrayList("dora", "emil", "friedrich")));
Map<String, User> map = new LinkedHashMap<String, User>();
for (int i = 0; i < users.size(); i++) {
map.put(String.valueOf(i + 1), users.get(i));
}
System.out.printf(new Gson().toJson(map));
}
}