Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在json中转换Java数据_Java_Javascript_Json - Fatal编程技术网

在json中转换Java数据

在json中转换Java数据,java,javascript,json,Java,Javascript,Json,我在集合中有一个用户对象列表,但我想将其转换为JSON格式,以便在html页面上使用javascript读取JSON数据 List<UserWithEmbeddedContact> users=(List<UserWithEmbeddedContact>) q.execute(); if(!users.isEmpty()) { for(UserWithEmbeddedContact user:users) { System.out.println(

我在集合中有一个用户对象列表,但我想将其转换为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());
    }
}
List用户=(List)q.execute();
如果(!users.isEmpty()){
for(UserWithEmbeddedContact用户:用户){
System.out.println(“username=“+user.getUsername())+
“password=“+user.getPassword()+”mobile=“+user.getMobile());
}
}
您的答案是:

从他们的维基:

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

例:

List用户=(List)q.execute();
final-Type listType=new-TypeToken(){}.getType();
最终字符串json=new Gson().toJson(用户,列表类型);

用于Java。这很简单。

试试这个,它会将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);
}

}

请参阅此TypeToken和GSon类不可用。因此,如何将它们导入包中
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);
}