GSON解析JSON数组

时间:2016-07-18 16:11:42

标签: java json

我有一个像这样的JSON文件:

Route::get('/userimage/{filename}', [
    'uses' => 'UserController@getUserImage',
    'as' => 'account.image',
]);

模型类:

[
  {
    "id": "1",
    "name": "test1",
    "childrens": [
      {
        "id": "14",
        "name": "test2",
        "childrens": [

        ]
      }
    ]
  }
]

我的解析方法:

public class Model {

   private int id;
   private String name;
}

1 个答案:

答案 0 :(得分:1)

为什么不直接解析json字符串?这就是我所做的,实现了你想要的同样的东西:

public class GsonPlay {


    public static void main(String args[]) {

        String testString = "[{\"id\": \"1\",\"name\": \"test1\",\"childrens\": [{\"id\": \"14\",\"name\": \"test2\",\"childrens\": []}]}]";
        List<Model> modelList = parseJsonService(testString);
        System.out.println(modelList);
    }

    private static List<Model> parseJsonService(String testString) {
        Gson gson = new Gson();
        Model[] models = gson.fromJson(testString, Model[].class);
        return Arrays.asList(models);
    }
}
class Model {
    private int id;
    private String name;
    private List<Model> childrens;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Model> getChildrens() {
        return childrens;
    }

    public void setChildrens(List<Model> childrens) {
        this.childrens = childrens;
    }
}

您还可以查看this以获取更多想法: