将Json解析为Java bean

时间:2010-08-24 09:49:06

标签: java json exiftool

我正在尝试解析由Exiftool生成的这样的Json文件:

[{
  "SourceFile": "videos/XaviHernandez.flv",
  "ExifTool": {
    "ExifToolVersion": 8.22
  },
  "System": {
    "FileName": "XaviHernandez.flv",
    "Directory": "videos",
    "FileSize": "16 MB",
    "FileModifyDate": "2010:06:17 09:57:21+02:00",
    "FilePermissions": "rw-r--r--"
  },
  "File": {
    "FileType": "FLV",
    "MIMEType": "video/x-flv"
  }
}]

在具有此结构的Java bean中:

public class MetadataContentBean {
    ExifToolBean exiftoolBean;
    String SourceFile;
    FileBean fileBean;
    SystemBean systemBean;
//Getters and setter
}

我的java代码是这样的:

    InputStream is = this.getClass().getClassLoader().getResourceAsStream(filename);
    String jsonTxt = IOUtils.toString(is);
    JSONArray json = (JSONArray) JSONSerializer.toJSON(jsonTxt);
    JSONObject metadatacontent = json.getJSONObject(0);
    ObjectMapper mapper = new ObjectMapper();
    MetadataContentBean meta = new MetadataContentBean();
    mapper.readValue(metadatacontent.toString(), MetadataContentBean.class);
    meta= (MetadataContentBean) JSONObject.toBean(metadatacontent, MetadataContentBean.class);

但是我收到了这个错误:

net.sf.json.JSONException: java.lang.NoSuchMethodException: Unknown property 'ExifTool'
    at net.sf.json.util.PropertySetStrategy$DefaultPropertySetStrategy.setProperty(PropertySetStrategy.java:45)
    at net.sf.json.JSONObject.setProperty(JSONObject.java:1477)
    at net.sf.json.JSONObject.toBean(JSONObject.java:468)
    at net.sf.json.JSONObject.toBean(JSONObject.java:253)
    at com.playence.parser.JSon.Parser(JSon.java:66)
    at com.playence.parser.JSon.main(JSon.java:28)
Caused by: java.lang.NoSuchMethodException: Unknown property 'ExifTool'

我已经在几个论坛上查了一下,但解决方案就是这个,所以我不知道为什么我没有得到结果。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

ObjectMapper mapper = new ObjectMapper();
MetadataContentBean meta= mapper.readValue(metadatacontent.toString(), MetadataContentBean.class);

在这个元中是所有信息

答案 1 :(得分:0)

问题混合了com.fasterxml.jacksonnet.sf.json可互换的库。

@Blanca回答了杰克逊。这是net.sf.json的替代方案:

JSONArray json = (JSONArray) JSONSerializer.toJSON(jsonTxt);
JSONObject metadatacontent = json.getJSONObject(0);
MetadataContentBean meta = (MetadataContentBean) JSONObject.toBean(metadatacontent, MetadataContentBean.class);

抛出NoSuchMethodException: Unknown property 'ExifTool'是因为PropertySetStrategy.DEFAULT需要公共字段或设置器。