从json创建java对象列表

时间:2015-03-06 04:40:42

标签: java json gson

我有跟随json,我需要将其转换为java对象列表。

{
  "model":[

    {
        "syscall_1":"execve",
        "syscall_2":"brk"
    },
    {
        "syscall_1":"brk",
        "syscall_2":"access"
    },
    {
        "syscall_1":"access",
        "syscall_2":"mmap"
    },
    {
        "syscall_1":"mmap",
        "syscall_2":"access"
    }
]
}

我正在使用gson及其TypeToken>(){}。getType()API,但是我对我的对象看起来与输入json相对应的方式感到有点困惑。

如何在这种情况下使用TypeToken?

2 个答案:

答案 0 :(得分:1)

另一个选项(不使用类型标记,但仍能实现你想要的)将解析整个json对象,然后像这样访问模型数组:

import com.google.gson.Gson;

import java.util.List;


public class TestMe {

    public static void main(String[] args) {

        String jsonSt2 = "{\"model\":[{\"syscall_1\":\"execve\",\"syscall_2\":\"brk\"},{\"syscall_1\":\"brk\",\"syscall_2\":\"access\"},{\"syscall_1\":\"access\",\"syscall_2\":\"mmap\"},{\"syscall_1\":\"mmap\",\"syscall_2\":\"access\"}]}";
        System.out.println("your json: " + jsonSt2);

        ModelObject object = new Gson().fromJson(jsonSt2, ModelObject.class);

        System.out.println("Created Model object, array size is " + object.model.size());

        for (ModelItem mi : object.model) {
            System.out.println(mi.syscall_1 + " " + mi.syscall_2);
        }
    }
}

class ModelObject {
    List<ModelItem> model;
}

class ModelItem {
    String syscall_1;
    String syscall_2;
}

输出

Created Model object, array size is 4
execve brk
brk access
access mmap
mmap access
mmap access

答案 1 :(得分:0)

如果你可以使用org.json来解析和构造列表对象,你可以试试这个。

String jsonSt2 = "{\"model\":[{\"syscall_1\":\"execve\",\"syscall_2\":\"brk\"},{\"syscall_1\":\"brk\",\"syscall_2\":\"access\"},{\"syscall_1\":\"access\",\"syscall_2\":\"mmap\"},{\"syscall_1\":\"mmap\",\"syscall_2\":\"access\"}]}";
List<Model> models = new ArrayList<>();
JSONObject jsonModelObject = new org.json.JSONObject(jsonSt2);
Object modelObject = jsonModelObject.get("model");
if (modelObject instanceof JSONArray) {
JSONArray itemsArray =(JSONArray) modelObject;
for (int index = 0; index < itemsArray.length(); index++) {
    Model model = new Model();
    JSONObject modelItereative = (JSONObject) itemsArray.get(index);
    model.setSyscall_1(modelItereative.getString("syscall_1"));
    model.setSyscall_2(modelItereative.getString("syscall_1"));
    models.add(model);
}
}else if(modelObject instanceof JSONObject){
Model model = new Model();
JSONObject modelItereative = (JSONObject) modelObject;
model.setSyscall_1(modelItereative.getString("syscall_1"));
model.setSyscall_2(modelItereative.getString("syscall_1"));
models.add(model);
}
for(Model d22:models){
    System.out.println(d22.getSyscall_1() + " " + d22.getSyscall_2());
}