数组列表到json对象字符串的转换 [英] conversion of array list to json object string

查看:32
本文介绍了数组列表到json对象字符串的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型类方法,它返回一个包含所有注册用户详细信息的对象列表.我想获取由 all() 方法返回的列表并将数据转换为 JSON 对象并将其像字符串一样传递给视图.如何将此数组列表转换为 JSON 对象?

I have a model class method which returns a list of objects which contains all the registered user details. I want to fetch the list resturned by all() method and convert the data into JSON object and pass it to the view like a string. How can I do this conversion of this array list to JSON object?

我无法通过以下方式执行此操作:

I was unable to do this by below:

ObjectMapper mapper = new ObjectMapper();
JSONObject json = new JSONObject();
JsonNodeFactory jsonnode = JsonNodeFactory.instance;
ObjectNode result = new ObjectNode(jsonnode);
for (int i = 0; i < list.size(); i++) {
    json.put(list.get(i).fname, list.get(i));
    System.out.println(json.get("fname"));
}

@Entity
class Mydata extends Model {

    @Id
    public Long Id;
    public String fname;
    public String lname;
    public String city;
    public String state;
    /****************** READ/select OPERATION *****************/
    public static Finder < Long, Mydata > finder = new Finder(Long.class, Mydata.class);

    public static List < Mydata > all() {
        return finder.all();
    }
    public static void createuser(Mydata user) {
        user.save();
    }
}

推荐答案

要将 ArrayList 转换为 Json,只需从以下位置下载 Open Source json 实用程序:http://json.org/java/ 或来自 这里

To convert ArrayList to Json, just download Open Source json utility from: http://json.org/java/ or Jar file from here

然后就去做:

JSONArray jsonAraay = new JSONArray(your_array_list);

就这样

注意:你应该在你的 POJO/MODEL 类中有 setter/getter 来将 arraylist 转换为 json

Note: You should have setter/getter in your POJO/MODEL class to convert arraylist to json

这篇关于数组列表到json对象字符串的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆