【问题标题】:Convert Java data in json [duplicate]在json中转换Java数据[重复]
【发布时间】:2013-11-12 20:10:32
【问题描述】:

我有一个集合中的用户对象列表,但我想将其转换为 JSON 格式,以便在我的 html 页面上使用 javascript 读取该 json 数据。

List<UserWithEmbeddedContact> users=(List<UserWithEmbeddedContact>) q.execute();
if(!users.isEmpty()) {
    for(UserWithEmbeddedContact user:users) {
        System.out.println("username="+user.getUsername()+
            " password="+user.getPassword()+" mobile="+user.getMobile());
    }
}

【问题讨论】:

标签: java javascript json


【解决方案1】:

GSON 是你的答案:

来自他们的维基:

Gson 是一个 Java 库,可用于将 Java 对象转换为其 JSON 表示形式。它还可用于将 JSON 字符串转换为等效的 Java 对象。 Gson 可以处理任意 Java 对象,包括您没有源代码的预先存在的对象。

例如:

List<UserWithEmbeddedContact> users = (List<UserWithEmbeddedContact>) q.execute();

final Type listType = new TypeToken<List<UserWithEmbeddedContact>>(){}.getType();
final String json = new Gson().toJson(users, listType);

【讨论】:

  • TypeToken 和 GSon 类不可用。那么如何将它们导入我的包中
【解决方案2】:

对 Java 使用 json-lib。这很容易。

【讨论】:

    【解决方案3】:

    试试这个,它会将java实例变量转换成JSON

    import com.google.gson.Gson;
    
    public class ObjectToJSON {
    // declaring variables to be converted into JSON
    private int data1 = 100;
    private String data2 = "hello";
    private String[] details = { "IBM", "pune", "ind", "12345" };
    
    public static void main(String[] args) {
        // Creating the class object
        ObjectToJSON obj = new ObjectToJSON();
        // Creating Gson class object
        Gson gson = new Gson();
    
        // convert java object to JSON format and receiving the JSON String
        String json = gson.toJson(obj);
    
        System.out.println(json);
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2020-08-05
      • 2020-12-02
      • 2013-01-28
      • 2021-05-19
      • 1970-01-01
      • 2014-01-23
      • 2019-09-12
      • 2020-04-13
      • 1970-01-01
      相关资源
      最近更新 更多