有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何将JSON数组转换为Java列表。我在用斯文森

我试图在Java中将多个相同类型的对象转换为List。例如,我的json是:

{
    "Example": [
        {
            "foo": "a1",
            "bar": "b1",
            "fubar": "c1"
        },
        {
            "foo": "a2",
            "bar": "b2",
            "fubar": "c2"
        },
        {
            "foo": "a3",
            "bar": "b3",
            "fubar": "c3"
        }
    ]
}

我有一门课:

public class Example {
    private String foo;
    private String bar;
    private String fubar;
    public Example(){};
    public void setFoo(String f){
        foo = f;
    }
    public void setBar(String b){
        bar = b;
    }
    public void setFubar(String f){
        fubar = f;
    }
...
}

我希望能够将得到的json字符串转换为Example对象列表。我想这样做:

JSONParser parser = new JSONParser();
parser.addTypeHint(".Example[]", Example.class);
List<Example> result = parser.parse(List.class, json);

这样做会出现一个错误:

Cannot set property Example on class java.util.ArrayList

共 (2) 个答案

  1. # 1 楼答案

    我通过修改JSON的格式解决了这个问题:

    [
        {
            "foo": "a1",
            "bar": "b1",
            "fubar": "c1"
        },
        {
            "foo": "a2",
            "bar": "b2",
            "fubar": "c2"
        },
        {
            "foo": "a3",
            "bar": "b3",
            "fubar": "c3"
        }
    ]
    

    然后我使用了java代码:

    JSONParser parser = new JSONParser();
        ArrayList list = parser.parse(ArrayList.class, json);
        List<Example> result = new ArrayList<Example>();
        for(int i = 0 ; i < list.size() ; i++){
            HashMap<String, String> map = (HashMap) list.get(i);
            Example example = new Example();
            example.setFoo(map.get("foo"));
            example.setBar(map.get("bar"));
            example.setFubar(map.get("fubar"));
            result.add(example);
        }
    
  2. # 2 楼答案

    我有一个类似这样的JSON字符串:

    [
    {"author":"amahta","bookId":1,"bookName":"name"},
    {"author":"amahta2","bookId":2,"bookName":"name2"}
    ]
    

    并通过以下代码片段将其转换为列表:

    List<BookVO> listdata = new ArrayList<BookVO>();
    
    JSONArray jArray = JSONArray.fromObject(booklist);
    if (jArray != null) {
        for (int i = 0; i < jArray.size(); i++) {
            JSONObject obj = JSONObject.fromObject(jArray.get(i));
            listdata.add(new BookVO(Long.valueOf(obj.get("bookId")), obj.get("bookName"), obj.get("author")));
        }
    }
    

    我用网。旧金山。json lib jar文件