如何使用Gson将json数组转换为java bean数组

时间:2017-03-18 07:39:01

标签: java gson

我有json对象数组的字符串

String jarray=  "{
                    "jsonarray": [{
                        "row_id": "2",
                        "priorty_seq": "1",
                        "id": "2",

                    }, {
                        "row_id": "1",
                        "priorty_seq": "1",
                        "id": "3",

                    }, {
                        "row_id": "0",
                        "priorty_seq": "1",
                        "iid": "1",

                        "is_active_html": "<i class='fa fa-lg fa-warning' style='color:red'></i>&nbsp;<b>Inactive</b>"
                    }, {
                        "row_id": "6",
                        "priorty_seq": "1",
                        "id": "64",

                    }]
                    }";

这是数组字符串,现在我必须用java bean映射它

class JavaBean
       { 
         @SerializedName("row_id") String row_id;
         @SerializedName("priorty_seq")String priorty_seq;
         @SerializedName("id")String id ;   
        }

现在我要做的是将这个json对象映射到Javabean的List  我们有任何方法直接将这些方法映射到bean列表 将它们映射到json abject并迭代json数组

1 个答案:

答案 0 :(得分:0)

假设你可以摆脱&#34; jsonarray&#34;键,只需保持数组本身,你可以使用下面的代码轻松解决这个问题;

String jarray = "[" +
                "{id: '1', priorty_seq: '10', row_id: '100'}," +
                "{id: '2', priorty_seq: '20', row_id: '200'}," +
                "{id: '3', priorty_seq: '30', row_id: '300'}" +
                "]";
Type type = new TypeToken<Collection<JavaBean>>() {}.getType();
Collection<JavaBean> result = new Gson().fromJson(jarray, type);

来源:https://github.com/google/gson/blob/master/UserGuide.md#TOC-Array-Examples