2

我想从我的 java 对象中创建一个类似于此结构的 json 文件:

{“用户”:

 {"1" : 
     { "ids" : [1,2,3], "names" : ["anton","berta","charlie"] },

 {"2" :
     { "ids" : [4,5,6], "names" : ["dora","emil","friedrich"] },

...等等。

我的问题是我不知道如何生成第二层次的数字。在所有教程中,我发现层次结构名称是由类名或注释生成的,但我不能使用这种方式来创建我请求的名称。

有没有办法做到这一点,而无需编写一个巨大的方法来“手动”生成 json Stirng?

格雷茨

4

2 回答 2

0

我们以 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));
  }
}
于 2013-07-17T13:15:00.310 回答
0

创建每个 json 条目所需的代码并不多:

public static String toJson(int i, List<User> users) {
    StringBuilder sb = new StringBuilder("{\"").append(i).append("\" : { \"ids\" : [");
    for (User user : users)
        sb.append(user.getId()).append(",");
    sb.setCharAt(sb.length() - 1, ']');
    sb.append(", \"names\" : [\"");
    for (User user : users)
        sb.append(user.getName()).append("\",\"");
    return sb.replace(sb.length() - 2, sb.length(),"] } ,").toString();
}

使用这种方法,在您的时间段内将新用户添加到列表中并为每个列表分配一个序列号是一件小事。


这是一些完整的测试代码及其输出:

static class User {
    private final int id;
    private final String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

public static String toJson(int i, List<User> users) {
    StringBuilder sb = new StringBuilder("{\"").append(i).append("\" : { \"ids\" : [");
    for (User user : users)
        sb.append(user.getId()).append(",");
    sb.setCharAt(sb.length() - 1, ']');
    sb.append(", \"names\" : [\"");
    for (User user : users)
        sb.append(user.getName()).append("\",\"");
    return sb.replace(sb.length() - 2, sb.length(),"] } ,").toString();
}

public static void main(String[] args) {//throws Exception {
    List<User> users = new ArrayList<User>();
    users.add(new User(1, "anton"));
    users.add(new User(2, "berta"));
    users.add(new User(3, "charlie"));
    System.out.println(toJson(1, users));
 }

输出:

{"1" : { "ids" : [1,2,3], "names" : ["anton","berta","charlie"] } ,
于 2013-07-17T13:46:23.783 回答