0

我有一个集合中的用户对象列表,但我想将其转换为 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());
    }
}
4

3 回答 3

1

GSON is your answer:

From their wiki:

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Ex:

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

final Type listType = new TypeToken<List<UserWithEmbeddedContact>>(){}.getType();
final String json = new Gson().toJson(users, listType);
于 2013-11-12T11:50:54.247 回答
0

Use json-lib for Java. It's very easy.

于 2013-11-12T11:51:01.437 回答
0

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

}

于 2013-11-12T12:10:32.850 回答