【发布时间】:2013-05-11 12:55:17
【问题描述】:
这可能是一个重复的问题。请参考link。
我能够将一个 json 对象映射到 POJO。但是如何使用相同的 jackson 框架将 json 对象数组转换为 pojo。
private void jsonToPojo(){
ObjectMapper mapper=new ObjectMapper();
try {
User1 user1=mapper.readValue(readFromFile(), User1.class);
User1[] user2=mapper.readValue(readFromFile(), User1[].class);
System.out.println(user1);
Toast.makeText(getApplicationContext(), "inside try", 0).show();
} catch (JsonParseException e) {
// TODO Auto-generated catch block
Log.i("Exception", "jsonparseexception");
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
Log.i("Exception", "jsonmapping exception");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("Exception", "ioexception");
e.printStackTrace();
}
}
这是类用户对象。
public class User {
private int age = 23;
private String name = "amal";
private List<String> messages = new ArrayList<String>() {
{
add("hi");
add("how");
add("are u.");
}
};
//getter and setter methods
@Override
public String toString() {
return "User [age=" + age + ", name=" + name + ", " +
"messages=" + messages + "]";
}
这是我尝试做的:(readFromFile() 从文件中获取 json)
User1[] user2=mapper.readValue(readFromFile(), User1[].class);
jsonToPojo() 仅适用于一个对象。但是,如果我尝试上面的代码行,它不会采用以下 json:
[
{
"age":"23",
"messages":["hi","how","are u."],
"name":"amal"
},
{
"age":"98",
"messages":["Reply","my","question"],
"name":"You"
}
]
【问题讨论】:
-
我已经测试了你的示例 JSON,你的代码对我有用。 User 和 User1 类是相同的还是您有两个不同的类?
-
user1 是一个新类。好吧,我想将 json 对象数组存储在 pojo 中。这就是我无法做到的。